题意:求每个节点的最远距离
分析:dfs1 求出直径的两个端点, dfs2 遍历每个点到端点的距离( 因为最远距离在该点到直径中的一个端点 )
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <cmath>
using namespace std;
#define LL long long
#define INF 0x3f3f3f3f
#define fi first
#define se second
#define mem(a,b) memset((a),(b),sizeof(a))
const LL MAXV=100000+3;
struct Edge//边
{
LL to,cost;
Edge(LL t,LL c):to(t),cost(c){}
};
LL N,L,V1,V2,ans;
vector<Edge> G[MAXV];//邻接表存树
LL dp[MAXV],deep[MAXV],dis[2][MAXV];
void init()//初始化
{
for(LL i=1;i<=N;++i)
{
G[i].clear();
dp[i]=0;
deep[i]=i;
}
L=0;
ans=0;
}
void dfs1(LL u,LL fa)//树形dp求直径
{
LL the_max=0,the_second=0,v1=u,v2=u;
for(LL i=0;i<G[u].size();++i)
{
LL v=G[u][i].to;
if(v==fa)
continue;
dfs1(v,u);
LL now_dis=dp[v]+G[u][i].cost;
if(now_dis>the_max)
{
the_second=the_max;
v2=v1;
the_max=now_dis;
v1=deep[v];
}
else if(now_dis>the_second)
{
the_second=now_dis;
v2=deep[v];
}
}
dp[u]=the_max;
deep[u]=v1;
if(the_max+the_second>L)
{
L=the_max+the_second;
V1=v1;
V2=v2;
}
}
void dfs2(LL u,LL fa,LL id)//求某一个点到其他距离的点
{
for(LL i=0;i<G[u].size();++i)
{
LL v=G[u][i].to;
if(v==fa)
continue;
dis[id][v]=dis[id][u]+G[u][i].cost;
dfs2(v,u,id);
}
}
int main()
{
while(~scanf("%lld",&N))
{
init();
for(LL i=2;i<=N;++i)
{
LL a,b,c;
scanf("%lld%lld",&a,&b);
G[i].push_back(Edge(a,b));
G[a].push_back(Edge(i,b));
}
dfs1(1,-1);
memset(dis,0,sizeof(dis));
dfs2(V1,-1,0);
dfs2(V2,-1,1);
for(LL u=1;u<=N;++u)
{
if(u==V1||u==V2)
cout << L << endl;
else cout << max(dis[0][u],dis[1][u]) << endl;
}
}
return 0;
}