1094-farthest Nodes in a Tree
PDF (中文版) statisticsforum
Time Limit:2 second (s) Memory limit:32 MB
Given a tree (a connected graph with no cycles), you have to find the farthest nodes in the tree. The edges of the tree is weighted and undirected. That's means you had to find nodes in the whose distance was maximum amongst all nodes.
Input
Input starts with an integer T (≤10), denoting the number of test cases.
Each case starts with a integer n (2≤n≤30000) denoting the total number of nodes in the tree. The nodes is numbered from 0 to n-1. Each of the next n-1 lines would contain three integers u v w (0≤u, v < N, u≠v, 1≤w≤10000) denoting that node u and V are connected by a edge whose weight is W. You can assume that the input would form a valid tree.
Output
For each case, print the case number and the maximum distance.
Sample Input
Output for Sample Input
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
Notes
The Dataset is huge, and the use faster I/O methods.
Idea: Starting from the 0 node Dfs out of a longest path (because it is the diameter of the tree, it is definitely two longest side, but not sure is 0, so first DFS out of one), with the path leaf node as the root, and then Dfs out the longest path.
#include <iostream>#include<cstring>#include<cstdio>#include<algorithm>using namespacestd;Const intN =30010;structedge{intU,v,w,next; Edge () {}; Edge (intUintVintWintnext): U (U), V (v), W (W), Next (next) {}; }e[2*N];intHead[n],tot,t,n,maxn,pos;voidAddedge (intUintVintW) {//turn a multi-fork tree into a binary treeE[tot] =Edge (U,v,w,head[u]); Head[u]= tot++; E[tot]=Edge (V,u,w,head[v]); HEAD[V]= tot++;}voidDfsintUintVintW) {//V is to reverse the inverse of Dfs will result in an infinite loop causing stack overflow intChild =0; for(inti=head[u];i!=-1; i = e[i].next) {//cout<<i<<endl; if(E[I].V==V)Continue; DFS (E[I].V,U,E[I].W+W); Child++; } if(child==0&&w>MAXN) {MAXN=W; POS= u;//cout<< "" <<w<<endl; } return ;}intMain () {intu,v,w; scanf ("%d",&T); for(intt=1; t<=t;t++) {tot=0; memset (Head,-1,sizeof(head)); scanf ("%d",&N); for(intI=1; i<n;i++) {scanf ("%d%d%d",&u,&v,&W); Addedge (U,V,W); } MAXN=0; DFS (0,-1,0); MAXN=0; //cout<<pos<<endl;DFS (pos,-1,0); printf ("Case %d:%d\n", T,MAXN); } return 0;}
lightoj-1094 farthest Nodes in a tree (to find the diameter of trees)