Test instructions: Given a tree of n points, ask for the maximum distance from each point in the tree to the other points in the tree.
n<=10000
Idea: Set f[u,1],f[u,2] for the longest with u as the root down and the undersecretary, g[u,1],g[u,2] for from which son transferred from
For the first time DFS with V update u, the second DFS with U update v, because there is a situation where V to u goes up, this can be handled
You can see that the maximum value of these values is the diameter of the tree.
1 varF,g:Array[1..21000,1..2] ofLongint;2Head,vet,next,len:Array[1..21000] ofLongint;3 N,x,y,i,tot:longint;4 5 procedureAdd (a,b,c:longint);6 begin7 Inc (TOT);8next[tot]:=Head[a];9vet[tot]:=b;Tenlen[tot]:=C; Onehead[a]:=tot; A End; - - procedureDFS (u,fa:longint); the varE,v,t:longint; - begin -e:=Head[u]; - whileE<>0 Do + begin -v:=Vet[e]; + ifV<>fa Then A begin at DFS (v,u); -T:=f[v,1]+Len[e]; - ifT>f[u,1] Then - begin -F[u,2]:=f[u,1]; G[u,2]:=g[u,1]; -F[u,1]:=t; G[u,1]:=v; in End - Else ifT>f[u,2] Then to begin +F[u,2]:=t; G[u,2]:=v; - End; the End; *e:=Next[e]; $ End;Panax Notoginseng End; - the procedureDFS2 (u,fa:longint); + varE,v,t:longint; A begin thee:=Head[u]; + whileE<>0 Do - begin $v:=Vet[e]; $ ifV<>fa Then - begin -T:=f[u,1]+Len[e]; the ifV=g[u,1] ThenT:=f[u,2]+Len[e]; - ifT>f[v,1] ThenWuyi begin theF[v,2]:=f[v,1]; G[v,2]:=g[v,1]; -F[v,1]:=t; G[v,1]:=u; Wu End - Else ifT>f[v,2] Then About begin $F[v,2]:=t; G[v,2]:=u; - End; - DFS2 (v,u); - End; Ae:=Next[e]; + End; the End; - $ begin theAssign (input,'2196.in'); Reset (input); theAssign (output,'2196.out'); Rewrite (output); the while notEof Do the begin -Fillchar (Head,sizeof (head),0); intot:=0; theFillchar (F,sizeof (f),0); theFillchar (G,sizeof (g),0); About read (n); the ifn=0 ThenBreak ; the fori:=2 toN Do the begin + read (x, y); - Add (i,x,y); the Add (x,i,y);Bayi End; theDfs1,-1); theDFS2 (1,-1); - fori:=1 toN DoWriteln (F[i,1]); - End; the close (input); the close (output); the End.
"HDOJ2196" computer (tree diameter, tree dp)