题目链接:http://acm.split.hdu.edu.cn/showproblem.php?pid=2196

给你n个点,n-1条边,然后给你每条边的权值。输出每个点能对应其他点的最远距离是多少。

树形dp,2次dfs。

第一次 dfs1自低向上回溯更新:dp[i][0]表示从底部到i点的最远距离,dp[i][1]则表示次远距离 (dp[i][2]时用到)

dp[i][0] = max(dp[i][0], dp[i的子节点][0] + edge);

第二次 dfs2自顶向下顺着更新:dp[i][2]表示从前部到i点的最远距离,顺着下来。

1)要是dp[i父节点][0]由i点转移 :dp[i][2] = max(dp[i父节点][2] , dp[i父节点][1]) + edge;

      当然只有一条边的话就:dp[i][2] = dp[i父节点][2];

2)否则 :dp[i][2] = max(dp[i父节点][2] , dp[i父节点][0]) + edge;

 //HDU 2196
//#pragma comment(linker, "/STACK:102400000, 102400000")
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <vector>
#include <cmath>
#include <ctime>
#include <list>
#include <set>
#include <map>
using namespace std;
typedef long long LL;
typedef pair <int, int> P;
const int N = 1e5 + ;
struct Edge {
int next, to, cost;
}edge[N << ];
int dp[N][], head[N], cnt; inline void add(int u, int v, int c) {
edge[cnt].to = v;
edge[cnt].next = head[u];
edge[cnt].cost = c;
head[u] = cnt++;
} void dfs1(int u, int p) {
for(int i = head[u]; ~i; i = edge[i].next) {
int v = edge[i].to;
if(v == p)
continue;
dfs1(v, u);
if(edge[i].cost + dp[v][] >= dp[u][]) {
dp[u][] = dp[u][];
dp[u][] = dp[v][] + edge[i].cost;
} else {
dp[u][] = max(dp[v][] + edge[i].cost, dp[u][]);
}
}
} void dfs2(int u, int p, int val) {
for(int i = head[u]; ~i; i = edge[i].next) {
int v = edge[i].to;
if(v == p)
continue;
if(dp[u][] == dp[v][] + edge[i].cost) {
dp[v][] = max(dp[u][], val) + edge[i].cost;
} else {
dp[v][] = max(dp[u][], val) + edge[i].cost;
}
dfs2(v, u, dp[v][]);
}
} int main()
{
int n, u, v;
while(~scanf("%d", &n)) {
memset(head, -, sizeof(head));
cnt = ;
for(int i = ; i <= n; ++i) {
scanf("%d %d", &u, &v);
add(i, u, v);
add(u, i, v);
}
memset(dp, , sizeof(dp));
dfs1(, -);
dfs2(, -, );
for(int i = ; i <= n; ++i) {
printf("%d\n", max(dp[i][], dp[i][]));
}
}
return ;
}