题目大意:在一棵树上,求每个节点到树上任意结点的最远距离。
解题思路:利用性质——"树上任意某个节点到树上任意节点的最远距离的端点一定会是
树上直径的两个端点之一。”,第一次dfs从根节点开始找出树的直径的其中一个端点,然
后从这个端点dfs,再从另一个端点dfs,max一下的最远距离则是所求答案。
/* ***********************************************
┆ ┏┓ ┏┓ ┆
┆┏┛┻━━━┛┻┓ ┆
┆┃ ┃ ┆
┆┃ ━ ┃ ┆
┆┃ ┳┛ ┗┳ ┃ ┆
┆┃ ┃ ┆
┆┃ ┻ ┃ ┆
┆┗━┓ 马 ┏━┛ ┆
┆ ┃ 勒 ┃ ┆
┆ ┃ 戈 ┗━━━┓ ┆
┆ ┃ 壁 ┣┓┆
┆ ┃ 的草泥马 ┏┛┆
┆ ┗┓┓┏━┳┓┏┛ ┆
┆ ┃┫┫ ┃┫┫ ┆
┆ ┗┻┛ ┗┻┛ ┆
************************************************ */
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <bitset>
using namespace std;
#define rep(i,a,b) for (int i=(a),_ed=(b);i<=_ed;i++)
#define per(i,a,b) for (int i=(b),_ed=(a);i>=_ed;i--)
#define pb push_back
#define mp make_pair
const int inf_int = 2e9;
const long long inf_ll = 2e18;
#define inf_add 0x3f3f3f3f
#define mod 1000000007
#define LL long long
#define ULL unsigned long long
#define MS0(X) memset((X), 0, sizeof((X)))
#define SelfType int
SelfType Gcd(SelfType p,SelfType q){return q==0?p:Gcd(q,p%q);}
SelfType Pow(SelfType p,SelfType q){SelfType ans=1;while(q){if(q&1)ans=ans*p;p=p*p;q>>=1;}return ans;}
#define Sd(X) int (X); scanf("%d", &X)
#define Sdd(X, Y) int X, Y; scanf("%d%d", &X, &Y)
#define Sddd(X, Y, Z) int X, Y, Z; scanf("%d%d%d", &X, &Y, &Z)
#define reunique(v) v.resize(std::unique(v.begin(), v.end()) - v.begin())
#define all(a) a.begin(), a.end()
typedef pair<int, int> pii;
typedef pair<long long, long long> pll;
typedef vector<int> vi;
typedef vector<long long> vll;
inline int read(){int ra,fh;char rx;rx=getchar(),ra=0,fh=1;while((rx<'0'||rx>'9')&&rx!='-')rx=getchar();if(rx=='-')fh=-1,rx=getchar();while(rx>='0'&&rx<='9')ra*=10,ra+=rx-48,rx=getchar();return ra*fh;}
//#pragma comment(linker, "/STACK:102400000,102400000")
const int maxn = 1e4 + 5;
struct Edge
{
int to,nx,w;
}edge[maxn*2];
int head[maxn],cnt,dp[maxn];
int mx_len,End;
void addedge(int u,int v,int w)
{
edge[cnt] = Edge {v,head[u],w};
head[u] = cnt++;
edge[cnt] = Edge {u,head[v],w};
head[v] = cnt++;
}
void dfs(int x,int fa,int len)
{
if(len>mx_len)
{
mx_len = len;
End = x;
}
for(int i=head[x];i;i=edge[i].nx)
{
int v = edge[i].to;
if(v!=fa)
{
int w = edge[i].w;
dfs(v,x,len+w);
dp[v] = max(dp[v],len+w);
}
}
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
ios::sync_with_stdio(0);
cin.tie(0);
int n;
while(~scanf("%d",&n))
{
MS0(head);
MS0(dp);
cnt = 1;
mx_len = 0;
for(int v=2;v<=n;v++)
{
int u,w;
scanf("%d%d",&u,&w);
addedge(u,v,w);
}
dfs(1,0,0);
//从树的直径的两端开始dfs
dfs(End,0,0);
dfs(End,0,0);
for(int i=1;i<=n;i++)
printf("%d\n",dp[i]);
}
return 0;
}