Main topic:
Each new computer has a length attached to a single computer, asking for the distance of each computer from its farthest computer.
This is because the first computer is the original, so the first computer can be used as the root, and the other computers can be distributed to form a tree.
There are two kinds of distance here, one is to look at the tree bottom, one is to go toward the parent node direction
The maximum distance that each node in the first DFS record finds its tree bottom in the direction of the child node, and the second DFS record the largest distance that each node can get if it starts to move toward the parent node
And finally judging the two to get a maximum value on the line
1#include <cstdio>2#include <cstring>3#include <iostream>4 using namespacestd;5 6 Const intN =10005;7 8 intFirst[n], maxn[n][4], K, vis[n];9 /*Ten Maxn[i][0] represents the longest distance I descend to the bottom of its tree, One Maxn[i][1] represents the distance to the bottom of the tree, A Maxn[i][2] Indicates the maximum distance the I node looks up - Finally, as long as the comparison of the something else is down to find the maximum distance can be - */ the structedge{ - inty, Next, D; -}e[n<<1]; - + voidAdd_edge (intXintYintd) - { +E[k].y = y, e[k].d = d, E[k].next =First[x]; AFIRST[X] = k++; at } - - voidMy_swap (int&x,int&y) - { - inttemp =x; -x = y, y =temp; in } - to voidDFS1 (intu) + { -Vis[u] =1; the for(inti = First[u]; i!=-1; I=E[i].next) { * intv =e[i].y; $ if(!Vis[v]) {Panax Notoginseng DFS1 (v); - //Update the undersecretary and maximum values, updated from bottom up, so write back after Dfs for backtracking the if(maxn[u][1] < maxn[v][0] +e[i].d) { +maxn[u][1] = maxn[v][0] +e[i].d; A if(maxn[u][0] < maxn[u][1]) theMy_swap (maxn[u][0], maxn[u][1]); + } - } $ } $ } - - voidDFS2 (intu) the { -Vis[u] =1;Wuyi for(intI= First[u]; i!=-1; I=E[i].next) { the intv =e[i].y; - if(!Vis[v]) { Wu //top-down update, so write in front of Dfs - //determines whether the maximum value falls on the current branch About inttmp; $ if(maxn[u][0]-maxn[v][0] ==e[i].d) -TMP = maxn[u][1]; - ElseTMP = maxn[u][0]; -maxn[v][2] = max (maxn[u][2], TMP) +e[i].d; A DFS2 (v); + } the } - } $ the intMain () the { the //freopen ("a.in", "R", stdin); the intN, D, A; - while(SCANF ("%d", &n) = =1) in { theK =0; thememset (First,-1,sizeof(first)); About for(intI=2; I<=n; i++){ thescanf"%d%d", &a, &d); the Add_edge (A, I, d); the Add_edge (i, A, d); + } - thememset (MAXN,0,sizeof(MAXN));Bayimemset (Vis,0,sizeof(Vis)); theDFS1 (1); the -memset (Vis,0,sizeof(Vis)); -DFS2 (1); the /* the for (int i=1; i<=n; i++) the printf ("%d%d%d\n", maxn[i][0], maxn[i][1], maxn[i][2]); the */ - for(intI=1; I<=n; i++) theprintf"%d\n", Max (maxn[i][0], maxn[i][2])); the } the return 0;94}
HDU 2196 Computer Tree DP