Title Link: http://poj.org/problem?id=1849
Test instructions: There is an n-node-weighted, non-oriented tree that puts two robots in the S node, and the two robots will walk through each side of the tree, but the robot does not need to return to its starting point. What is the minimum value of the sum of the total length of the two robots going?
Analysis: If you go through a tree and come back from a certain point, then all sides will walk two times, and from some point there are two robots to go to traverse, because do not come back, so the last two people the farther away the better, can be from the diameter of the tree a point in the opposite, then this distance (the diameter of the tree) only walked over, the other to walk two times , so the Ans=sum*2-len (the diameter of the total side length and the *2-tree).
#include <cstdio>#include<cstring>#include<cmath>#include<iostream>#include<algorithm>#include<queue>#include<cstdlib>#include<stack>#include<vector>#include<Set>#include<map>#defineLL Long Long#defineMoD 1000000007#defineINF 0x3f3f3f3f#defineN 100010#defineCLR (a) (Memset (A,0,sizeof (a)))using namespacestd;structedge{intV,w,next; Edge () {} Edge (intVintWintnext): V (v), W (W), Next (next) {}}e[2*N];inthead[n],tot,n,m,mx,s;voidAddedge (intUintVintW) {E[tot]=Edge (V,w,head[u]); Head[u]=tot++;}voidDfsintUintFaintLen) { if(LEN>MX) mx=len,s=u; for(intI=head[u];~i;i=E[i].next) { intv=e[i].v,w=E[I].W; if(V==FA)Continue; DFS (V,u,len+W); }}intMain () {intu,v,w,sum; while(SCANF ("%d%d", &n,&m) >0) {memset (head,-1,sizeof(head)); Tot=0; sum=0; for(intI=1; i<n;i++) {scanf ("%d%d%d",&u,&v,&W); Addedge (U,V,W); Addedge (V,U,W); Sum+=w*2; } MX=0; DFS (M,-1,0); DFS (S,-1,0); printf ("%d\n", sum-MX); }}View Code
poj1849 (diameter of tree)