Calculate the maximum distance between nodes.
First, DFS records the maximum distance (DP [u] [0]) and the second distance (DP [u] [1]) under each node's subtree.
Use DP [v] [2] to indicate the maximum distance from the parent node of v.
Obtain the maximum values of DP [u] [0] and DP [u] [2 ].
# Include <cstdio> # include <cstring> # include <cstdlib> # include <string> # include <iostream> # include <algorithm> # include <sstream> # include <cmath> using namespace STD; # include <queue> # include <stack> # include <vector> # include <deque> # include <set> # include <map> # include <time. h >;# define CLer (ARR, Val) memset (ARR, Val, sizeof (ARR) # define for (I, a, B) for (INT I =; I <= B; I ++) # define in freopen ("in.txt", "R", Stdin); # define out freopen ("out.txt", "W", stdout); typedef long ll; const int maxn = 10014; const int maxm = 20014; const int INF = 0x3f3f3f; const int mod = 1000000007; struct node {int V, next; ll val;} edge [maxm]; int head [maxm], Tol; ll DP [maxn] [3]; bool vis [maxn]; void Init () {CLer (Head,-1); Tol = 0;} void addedge (int u, int V, ll Val) {edge [tol]. V = V, edge [tol]. val = Val, edge [tol]. next = head [u]; head [U] = tol ++; edge [tol]. V = u, edge [tol]. val = Val, edge [tol]. next = head [v]; head [v] = tol ++;} void dfs1 (int u) {If (vis [u]) return; vis [u] = true; for (INT I = head [u]; ~ I; I = edge [I]. Next) {int v = edge [I]. V; If (! Vis [v]) {dfs1 (V); DP [u] [1] = max (DP [u] [1], DP [v] [0] + edge [I]. val); If (DP [u] [1]> DP [u] [0]) Swap (DP [u] [1], DP [u] [0]) ;}} void dfs2 (int u) {If (vis [u]) return; vis [u] = true; for (INT I = head [u]; ~ I; I = edge [I]. Next) {int v = edge [I]. V, val = edge [I]. Val; If (! Vis [v]) {If (DP [u] [0]> DP [v] [0] + val) // DP [u] [0] is not DP [v] [0] + val [v] [2] = max (DP [v] [2], max (DP [u] [0] + val, DP [u] [2] + val )); // Therefore, the longer else from the non-V subtree // DP [u] [0] DP [v] [0] + val [v] [2] = max (DP [v] [2], max (DP [u] [1] + val, DP [u] [2] + val )); // determine the dfs2 (V);} int main () {# ifndef online_judge freopen ("in.txt", "r", stdin) from a non-V subtree ); # endif int N; while (~ Scanf ("% d", & N) {Init (); For (INT I = 2; I <= N; I ++) {int A; ll B; scanf ("% d % i64d", & A, & B); addedge (I, a, B) ;}cler (VIS, false); CLer (DP, 0 ); dfs1 (1); CLer (VIS, false); dfs2 (1); For (INT I = 1; I <= N; I ++) printf ("% i64d \ n", max (DP [I] [2], DP [I] [0]);}
[Tree-like DP] HDU 2196 computer