A school bought the first computer some time ago(so this computer's id is 1). During the recent years the school bought N-1 new computers. Each new computer was connected to one of settled earlier. Managers of school are anxious about slow functioning of the net and want to know the maximum distance Si for which i-th computer needs to send signal (i.e. length of cable to the most distant computer). You need to provide this information.
Hint: the example input is corresponding to this graph. And from the graph, you can see that the computer 4 is farthest one from 1, so S1 = 3. Computer 4 and 5 are the farthest ones from 2, so S2 = 2. Computer 5 is the farthest one from 3, so S3 = 3. we also get S4 = 4, S5 = 4.
Input
Input file contains multiple test cases.In each case there is natural number N (N<=10000) in the first line, followed by (N-1) lines with descriptions of computers. i-th line contains two natural numbers - number of computer, to which i-th computer is connected and length of cable used for connection. Total length of cable does not exceed 10^9. Numbers in lines of input are separated by a space.
Output
For each case output N lines. i-th line must contain number Si for i-th computer (1<=i<=N).
Sample
严正声明:本文虽不是直接抄袭吾仄lo咚锵大佬的,但是完全是从他的推文中学来的,而且这里我也不具体讲解题方法,只提供我个人的代码,和大佬的差不多,这是大佬推文:动态规划-树形DP_吾仄lo咚锵的博客-CSDN博客(大佬详讲)。
省流:就是要尊重老师但是不私密
#include<iostream>
#include<algorithm>
#include<map>
#include<cmath>
#include<cstring>
#include<iomanip>
#include<numeric>
#include<stack>
#include<queue>
#include<set>
#include<string>
#include<vector>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int inf=0x3f3f3f3f,maxn=1e4+5;
//本题解法秒就秒在可以分最长路上和非最长路上讨论!
struct edge{
int v,w;
};
vector<edge> g[maxn];
int dp[maxn][3];//0是最长,1是亚长,2是向上走最长(0,1都是向下走)
void dfs1(int u)//向下走
{
int l1=0,l2=0;
for(auto e:g[u])
{
int v=e.v,w=e.w;
dfs1(v);
if(dp[v][0]+w>l1)
{
l2=l1;
l1=dp[v][0]+w;
}
else if(dp[v][0]+w>l2)l2=dp[v][0]+w;
}
dp[u][0]=l1;
dp[u][1]=l2;
}
void dfs2(int u)//计算向上走的最长路
{
for(auto e:g[u])
{
int v=e.v,w=e.w;
if(dp[v][0]+w==dp[u][0])//在最长上
dp[v][2]=max(dp[u][2],dp[u][1])+w;
else //不是最长
dp[v][2]=max(dp[u][0],dp[u][2])+w;
dfs2(v);
}
}
int main()
{
ios_base::sync_with_stdio(0),cin.tie(0);
int n;
while(cin>>n)
{
for(int i=0;i<maxn;i++)g[i].clear();//while(cin>>n)
memset(dp,0,sizeof dp);
for(int v=2;v<=n;v++)
{
int u,w;
cin>>u>>w;
g[u].push_back({v,w});
}
dfs1(1);
dp[1][2]=0;
dfs2(1);
for(int i=1;i<=n;i++)cout<<max(dp[i][0],dp[i][2])<<"\n";
}
return 0;
}