UVA - 10308 Roads in the North

题意:在一棵二叉树里找最远的两个点的距离,题目的输入和树的构建的看了好久,保存邻接边的信息,每次将一个节点加进树里,因为每次输入都要有输出,即:每次都要更新最大值,所以DFS一次就可以了,判断是否存在环,不然会RE

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int MAXN = 10100;

long long ans = 0;
int p[MAXN],next[MAXN];
int u[MAXN],v[MAXN],w[MAXN],x,y,z;

long long dfs(int V,int k){
    long long Max = 0;
    for (int e = p[V]; e != -1; e = next[e]){
        if (v[e] != k){ 
            long long sum = dfs(v[e],V) + w[e];
            if (ans < Max+sum)
                ans = Max + sum;
            if (Max < sum)
                Max = sum;
        }
    }
    return Max;
}

int main(){
    int cnt = 0;
    ans = 0;
    memset(p,-1,sizeof(p));
    char str[100];
    while (1){
        char *k = gets(str);
        if (k == NULL){
            dfs(1,-1);
            printf("%lld\n",ans);
            break;
        }
        else if (str[0] == '\0'){
            dfs(1,-1);
            printf("%lld\n",ans);
            cnt = 0,ans = 0;
            memset(p,-1,sizeof(p));
            continue;
        }
        sscanf(str,"%d%d%d",&x,&y,&z);
        u[cnt] = x,v[cnt] = y,w[cnt] = z;
        next[cnt] = p[x],p[x] = cnt;
        cnt++;
        u[cnt] = y,v[cnt] = x,w[cnt] = z;
        next[cnt] = p[y],p[y] = cnt;
        cnt++;
    }
    return 0;
}


你可能感兴趣的:(UVA - 10308 Roads in the North)