Title Link: http://acm.split.hdu.edu.cn/showproblem.php?pid=2196
Problem Description
A School bought the first computer some time ago (so this computer ' s ID is 1). During The recent years the school bought N-1 new computers. Each new computer is connected to one of settled earlier. Managers of school is anxious about slow functioning of the net and want to know the maximum distance Si for which i-th C Omputer needs to send signal (i.e. length of cable-the most distant computer). You need to provide this information.
Inputinput file contains multiple test cases. In each case there was natural number N (n<=10000) in the first line, followed by (N-1) lines with descriptions of Compu Ters. I-th line contains-natural numbers-number of computer, to which i-th computer is connected and length of cable used for connection. Total length of cable does not exceed 10^9. Numbers in lines of input is separated by a space. Outputfor each case output N lines. I-th line must contain number Si for i-th computer (1<=i<=n). Sample Input51 1 Sample OUTPUT3 2 3 4 4
Solution One, I think this is a bit messy, code implementation is not good understanding.
Code:
#include <iostream>#include<cstdio>#include<algorithm>#include<cstring>using namespacestd;Const intmaxn=10005;structnode{intv; intLen; intNext;} NODE[MAXN<<1];intHEAD[MAXN];intFM[MAXN],FN[MAXN];///The maximum distance, and the number of the corresponding subtreeintSM[MAXN],SN[MAXN];///and its corresponding sub-treeintK;voidAddedge (intUintVintl) {NODE[K].V=W; Node[k].len=M; Node[k].next=Head[u]; Head[u]=k++; NODE[K].V=u; Node[k].len=l; Node[k].next=Head[v]; HEAD[V]=k++;}voidDFS1 (intUintP///The first time DFS finds the maximum length of the subtree, and the number of the subtree of the maximum length{Fm[u]=0;///Initializesm[u]=0; for(intI=head[u]; i!=-1; I=Node[i].next) { intv=node[i].v; if(v==p)Continue; DFS1 (V,u); if(node[i].len+fm[v]>Sm[u]) {Sm[u]=node[i].len+Fm[v]; Sn[u]=v; if(sm[u]>Fm[u]) {swap (fm[u],sm[u]); Swap (Fn[u],sn[u]); } } }}voidDFS2 (intUintp) { for(intI=head[u]; i!=-1; I=Node[i].next) { intv=node[i].v; if(v==p)Continue; if(v==Fn[u]) { if(node[i].len+sm[u]>Sm[v]) {Sm[v]=node[i].len+Sm[u]; SN[V]=u; if(sm[v]>Fm[v]) {swap (fm[v],sm[v]); Swap (fn[v],sn[v]); } } } Else { if(node[i].len+fm[u]>Sm[v]) {Sm[v]=node[i].len+Fm[u]; SN[V]=u; if(sm[v]>Fm[v]) {swap (fm[v],sm[v]); Swap (fn[v],sn[v]); }}} DFS2 (V,u); }}intMain () {intN; while(SCANF ("%d", &n) = =1) {memset (head,-1,sizeof(head)); K=0; intx,l; for(intI=2; i<=n; i++) {scanf ("%d%d",&x,&l); Addedge (i,x,l); } DFS1 (1,-1);///pick a little bit as the root, then his father's knot is set to-1 .DFS2 (1,-1);///so change to DFS1 (2,-1), DFS2 (2,-1) is also possible for(intI=1; i<=n; i++) printf ("%d\n", Fm[i]); } return 0;}
hdu2196 Tree DP