标签:
Given a tree (a connected graph with no cycles), you have to find the farthest nodes in the tree. The edges of the tree are weighted and undirected. That means you have to find two nodes in the tree whose distance is maximum amongst all nodes.
Input
Input starts with an integer T (≤ 10), denoting the number of test cases.
Each case starts with an integer n (2 ≤ n ≤ 30000) denoting the total number of nodes in the tree. The nodes are numbered from 0 to n-1. Each of the next n-1 lines will contain three integers u v w (0 ≤ u, v < n, u ≠ v, 1 ≤ w ≤ 10000) denoting that node u and v are connected by an edge whose weight is w. You can assume that the input will form a valid tree.
For each case, print the case number and the maximum distance.
2
4
0 1 20
1 2 30
2 3 50
5
0 2 20
2 1 10
0 3 29
0 4 50
Case 1: 100
Case 2: 80
1 #include<cstdio> 2 #include<string.h> 3 #include<algorithm> 4 #define M 30010 5 #include<queue> 6 using namespace std; 7 int a,b,c,head[M],ans,flag[M],sum[M],node,num,i,n; 8 /* head表示每个节点的头“指针” 9 num表示总边数 10 ans记录最后的结果 11 flag[]标记访问过的节点 12 sum[]表示以该节点结尾的最长路 13 */ 14 15 struct stu 16 { 17 int from,to,val,next; 18 }st[M*2]; 19 void add_edge(int u,int v,int w) 20 { 21 st[num].from=u; 22 st[num].to=v; 23 st[num].val=w; 24 st[num].next=head[u]; 25 head[u]=num++; 26 } 27 void bfs(int fir) 28 { 29 int u; 30 queue<int> que; 31 memset(flag,0,sizeof(flag)); 32 memset(sum,0,sizeof(sum)); 33 flag[fir]=1; 34 que.push(fir); 35 ans=0; 36 while(!que.empty()) 37 { 38 u=que.front(); 39 que.pop(); 40 for(i = head[u] ; i != -1 ; i = st[i].next) 41 { 42 if(!flag[st[i].to] && sum[st[i].to] < sum[u] + st[i].val) 43 { 44 sum[st[i].to]=sum[u]+st[i].val; 45 flag[st[i].to]=1; 46 if(ans < sum[st[i].to]) 47 { 48 ans=sum[st[i].to]; 49 node=st[i].to; //记录以fir为起点的最长路的端点 50 } 51 que.push(st[i].to); 52 } 53 } 54 55 } 56 } 57 int main() 58 { 59 int k=0; 60 int t; 61 scanf("%d",&t); 62 while(t--) 63 { 64 num=0; 65 memset(head,-1,sizeof(head)); 66 scanf("%d",&n); 67 for(i = 1 ; i < n ; i++) 68 { 69 scanf("%d %d %d",&a,&b,&c); 70 add_edge(a,b,c); 71 add_edge(b,a,c); 72 } 73 bfs(1); 74 bfs(node); 75 printf("Case %d: %d\n",++k,ans); 76 } 77 }
Farthest Nodes in a Tree (求树的直径)
标签:
原文地址:http://www.cnblogs.com/yexiaozi/p/5729709.html