标签:include pid ems acm printf clu 距离 val oid
经发现 ,答案就是到直径2个端点距离的较大值。然后先搞出直径,再从直径2端分别开始,求出每个点与它的距离,取较大值。
#include<bits/stdc++.h>
using namespace std;
const int N=10006;
int n,f[N],ans[N],num_edge,head[N],len,s,t;
struct edge{
int to,nex,val;
}e[N<<1];
void add(int from,int to,int len)
{
++num_edge;
e[num_edge].nex=head[from];
e[num_edge].to=to;
e[num_edge].val=len;
head[from]=num_edge;
}
void dfs(int u,int fa,int &pos)
{
if(f[u]>len)len=f[u],pos=u;
for(int i=head[u];i;i=e[i].nex)
{
int v=e[i].to,w=e[i].val;
if(v==fa)continue;
f[v]=f[u]+w;
dfs(v,u,pos);
}
}
int main()
{
while(scanf("%d",&n)==1)
{
memset(ans,0,sizeof(ans));
num_edge=0;
memset(head,0,sizeof(head));
memset(e,0,sizeof(e));
for(int i=2,w,v;i<=n;++i)
{
scanf("%d%d",&v,&w);
add(v,i,w);
add(i,v,w);
}
memset(f,0,sizeof(f));len=0;
dfs(1,-1,s);
memset(f,0,sizeof(f));len=0;
dfs(s,-1,t);
for(int i=1;i<=n;++i)ans[i]=f[i];
memset(f,0,sizeof(f));len=0;
dfs(t,-1,s);
for(int i=1;i<=n;++i)ans[i]=max(ans[i],f[i]);
for(int i=1;i<=n;++i)printf("%d\n",ans[i]);
}
}
标签:include pid ems acm printf clu 距离 val oid
原文地址:https://www.cnblogs.com/zzctommy/p/12361353.html