What is the maximum value of the distance from each point in the tree to all the leaf nodes?
Idea: This problem with DFS on both sides can, again is to ask the current point to the sub-tree in that direction of the maximum value and the second big value, the other is the father in the direction of the maximum value. The need for sub-tree direction of the second large value, because if the current point V to find the longest distance, the child tree inside the obvious can be obtained, but the father's direction is not sure, if the father takes the maximum path through the point V, then this is definitely wrong, so ask for a second large value, then, With the father's second big value plus the father's weight and the subtree direction of the comparison on the line.
The code is as follows:
#include <cstdio>#include<cstring>#include<algorithm>using namespacestd;Const intMAXN =11000;structEdge {intTo , Next, Len;}; Edge EDGE[MAXN*2];inttot, HEAD[MAXN];intMAXLEN[MAXN], SMAXLEN[MAXN];//maxlen Maximum Smaxlen secondary value of the subtree of the current nodeintMAXID[MAXN], SMAXID[MAXN];//Maxid the number of the child that should be the maximum value of the current node, Smaxidvoidinit () {memset (head,-1,sizeof(head)); Tot=0;}voidAddedge (intUintVintLen) {edge[tot].to=v; Edge[tot].len=Len; Edge[tot]. Next=Head[u]; Head[u]= tot++;}//find out the maximum and minor values for each node downvoidDFS1 (intUintFa//find the maximum distance of the root node with u{Maxlen[u]= Smaxlen[u] =0; for(inti = Head[u]; I! =-1; i =Edge[i]. Next) {intv =edge[i].to; if(v = =FA)Continue; DFS1 (V, u); if(Smaxlen[u] < Maxlen[v] +Edge[i].len) {Smaxlen[u]= Maxlen[v] +Edge[i].len; Smaxid[u]=v; if(Maxlen[u] <Smaxlen[u]) {Swap (Maxlen[u], smaxlen[u]); Swap (Maxid[u], smaxid[u]); } } }}//find the maximum value from the parent node and down from the current pointvoidDFS2 (intUintFA) { for(inti = Head[u]; I! =-1; i =Edge[i]. Next) {intv =edge[i].to; if(v = =FA)Continue; if(v = = Maxid[u])//here we ask for V instead of U, and DFS1, so if you go through V when you take the maximum value, then you have to use the secondary value when you pass the path from U . { if(Edge[i].len + smaxlen[u] >Smaxlen[v]) {Smaxlen[v]= Edge[i].len +Smaxlen[u]; SMAXID[V]=u; if(Maxlen[v] <Smaxlen[v]) {Swap (Maxlen[v], smaxlen[v]); Swap (Maxid[v], smaxid[v]); } } } Else//Otherwise, use the maximum value { if(Edge[i].len + maxlen[u] >Smaxlen[v]) {Smaxlen[v]= Edge[i].len +Maxlen[u]; SMAXID[V]=u; if(Maxlen[v] <Smaxlen[v]) {Swap (Maxlen[v], smaxlen[v]); Swap (Maxid[v], smaxid[v]); }}} dfs2 (V, u); }}intMain () {intN; while(~SCANF ("%d", &N)) {init (); intA, B; for(inti =2; I <= N; i++) {scanf ("%d%d", &a, &b); Addedge (I, A, b); Addedge (A, I, b); } DFS1 (1,0); DFS2 (1,0); for(inti =1; I <= N; i++) printf ("%d\n", Maxlen[i]); } return 0;}
HDU 2196 computer (tree-shaped DP)