您的位置:首页 > 其它

POJ - 2631 Roads in the North

2013-10-19 01:04 288 查看
题意:求树上最远的距离,两次的DFS就行了,保存的是邻接边的信息,还要判断不存在环,不然会RE

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

struct node{
    int to;
    int len;
    int next;
}eg[2*MAXN];
int head[MAXN];
int idx,nd,Max;

void addEdge(int st,int et,int len){
    eg[idx].to = et;
    eg[idx].len = len;
    eg[idx].next = head[st];
    head[st] = idx++;;
}

void dfs(int to,int fr,int dis){
    if (dis > Max){
        Max = dis;
        nd = to;
    }
    for (int i = head[to]; i != 0; i = eg[i].next){
        int a = eg[i].to;
        if (a != fr)
            dfs(a,to,dis+eg[i].len);
    }
}

int main(){
    int st,et,len;
    idx = 1;
    while (scanf("%d%d%d",&st,&et,&len) != EOF){
        addEdge(st,et,len);
        addEdge(et,st,len);
    }
    nd = 1;
    Max = -1;
    dfs(1,0,0);
    Max = -1;
    dfs(nd,0,0);
    printf("%d\n",Max);
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: