题干
走你
题解
#include<cstdio>
#include<vector>
#include<cstring>
#include<algorithm>
#define max(x,y) (x) > (y) ? (x) : (y)
#define min(x,y) (x) < (y) ? (x) : (y)
using namespace std;
struct Edge{
int u;
int val;
Edge(int _u, int _val):u(_u),val(_val){}
};
vector<Edge>vec[10010];
int dp[10010];
int dfs(int root){
if(dp[root] != -1)return dp[root];
int size = vec[root].size();
int ans = -1;
for(int i=0; i<size; i++){
int res = dfs(vec[root][i].u);
if(res == -1){
res = 0;
dp[vec[root][i].u] = 0;
}
int val = vec[root][i].val;
ans = max(ans, res + val);
}
return dp[root] = ans;
}
int result[10010];
void trees(int root, int length){
int size = vec[root].size();
result[root] = max(result[root], length);
result[root] = max(result[root], dp[root]);
int u, val, first = 0, second = -1, mymax;
for(int i=0;i<size;i++){
u = vec[root][i].u;
val = dp[u] + vec[root][i].val;
if(val > first)first = val;
}
bool flag = false;
for(int i=0;i<size;i++){
u = vec[root][i].u;
val = dp[u] + vec[root][i].val;
if(!flag && first == val){
flag = true;continue;
}
if(first != val && val > second)second = val;
else if(first == val && flag && val > second)second = val;
}
for(int i=0;i<size;i++){
u = vec[root][i].u;
val = vec[root][i].val;
if(first == dp[u] + vec[root][i].val){
mymax = second;
}else{
mymax = first;
}
trees(u, max(mymax + val, length + val));
}
}
int main(){
int N,u,val;
while(~scanf("%d",&N)){
vec[0].clear();
vec[1].clear();
for(int i=2;i<=N;i++){
vec[i].clear();
scanf("%d%d",&u,&val);
vec[u].push_back(Edge(i,val));
}
memset(dp, -1, sizeof(dp));
int a,b;
dfs(1);
memset(result, -1, sizeof(result));
trees(1, 0);
for(int i=1;i<=N;i++){
printf("%d\n",result[i]);
}
}
return 0;
}