It's a classic tree-DP title
debugging for a night, plus a morning, WA numerous times
and finally found turned out to be multiple sets of input! ! ! ! !
I'm furious!
How much wasted time!
Really served, with wide seeing vain "Input file contains multiple test cases"
finally added a while (scanf) before. . . . .
There are two answers to each node, this is a sub-tree node to its longest distance of a point, and one of the longest distance on the direction of its parent node
Code:
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int MaxSize = 10005;
struct node
{
ll w,to,next;
}q[10005];
ll head[MaxSize],d[MaxSize][3];
void dfs1(ll n)
{
ll st[10005],j=0;
for(int i=head[n];i!=-1;i=q[i].next)
{
dfs1(q[i].to);
d[n][0]=max(d[n][0],d[q[i].to][0]+q[i].w);
st[j++]=d[q[i].to][0]+q[i].w;
}
sort(st,st+j);
if(j>1)
{d[n][1]=st[j-2];}
return ;
}
void dfs2(ll n,ll f,ll w)
{
if(n!=f)
{
ll op=d[n][0]+w;
if(op==d[f][0])
{
d[n][2]=max(d[n][2],d[f][2]+w);
d[n][2]=max(d[n][2],d[f][1]+w);
}
else
{
d[n][2]=max(d[n][2],d[f][2]+w);
d[n][2]=max(d[n][2],d[f][0]+w);
}
}
for(int i=head[n];i!=-1;i=q[i].next)
{
dfs2(q[i].to,n,q[i].w);
}
return ;
}
int main()
{
ll n,a,b;
while(~scanf("%lld",&n)){
memset(head,-1,sizeof(head));
memset(d,0,sizeof(d));
ll cnt=1;
for(int i=2;i<=n;i++)
{
scanf("%lld %lld",&a,&b);
q[cnt].to=i;
q[cnt].w=b;
q[cnt].next=head[a];
head[a]=cnt;
cnt++;
}
dfs1(1);
dfs2(1,1,0);
for(int i=1;i<=n;i++)
{
cout<<max(d[i][0],d[i][2])<<endl;
}
}
return 0;
}