POJ 2631 Roads in the North (求树的直径)

Description

Building and maintaining roads among communities in the far North is an expensive business. With this in mind, the roads are build such that there is only one route from a village to a village that does not pass through some other village twice. 
Given is an area in the far North comprising a number of villages and roads among them such that any village can be reached by road from any other village. Your job is to find the road distance between the two most remote villages in the area. 

The area has up to 10,000 villages connected by road segments. The villages are numbered from 1. 

Input

Input to the problem is a sequence of lines, each containing three positive integers: the number of a village, the number of a different village, and the length of the road segment connecting the villages in kilometers. All road segments are two-way.

Output

You are to output a single integer: the road distance between the two most remote villages in the area.

Sample Input

5 1 6
1 4 5
6 3 9
2 6 8
6 1 7

Sample Output

22

 1 #include<cstdio>
 2 #include<queue>
 3 #include<string.h>
 4 #define M 100000
 5 using namespace std;
 6 int m,ans,flag[M],sum[M],n,a,b,c,i,head[M],num,node;
 7 struct stu
 8 {
 9     int from,to,val,next;
10 }st[M];
11 void init()
12 {
13     num=0;
14     memset(head,-1,sizeof(head));
15 }
16 void add_edge(int u,int v,int w)
17 {
18     st[num].from=u;
19     st[num].to=v;
20     st[num].val=w;
21     st[num].next=head[u];
22     head[u]=num++;
23 }
24 void bfs(int fir)
25 {    
26     ans=0;
27     int u;
28     memset(sum,0,sizeof(sum));
29     memset(flag,0,sizeof(flag));
30     queue<int>que;
31     que.push(fir);
32     flag[fir]=1;
33     while(!que.empty())
34     {
35     
36         u=que.front();
37         que.pop();
38         for(i = head[u] ; i != -1 ; i=st[i].next)
39         {
40             if(!flag[st[i].to] && sum[st[i].to] < sum[u]+st[i].val)
41             {
42                 sum[st[i].to]=sum[u]+st[i].val;
43                 if(ans < sum[st[i].to])
44                 {
45                     ans=sum[st[i].to];
46                     node=st[i].to;
47                 }
48                 flag[st[i].to]=1;
49                 que.push(st[i].to);
50             }
51         }
52     }
53 }
54 int main()
55 {    
56     init();
57     while(scanf("%d %d %d",&a,&b,&c)!=EOF)
58     {
59         add_edge(a,b,c);
60         add_edge(b,a,c);
61     }
62     
63         bfs(1);
64         bfs(node);
65         printf("%d
",ans);
66 }
67  //输入后Ctrl+Z输出结果
——将来的你会感谢现在努力的自己。
原文地址:https://www.cnblogs.com/yexiaozi/p/5730204.html