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 Input
5 1 1 2 1 3 1 1 1
Sample Output
3 2 3 4 4
题意:给出一颗树,n个点,n-1行,每行i,v两个数,后跟第k行代表第k+1个点连接第i个点,权为v。求每个点到最大权值的点的权。
思路:找某一个点作为树的根,设叶子到根为正方向,根到叶子为反方向。一个节点的最大权一定是连着根的。(把一个节点的根从当前节点分开,分成两部分,这个节点的最大权一定在这两个方向之一)
先正方向遍历一遍,求dp[u][0](代表正方向的根到当前点的最大值),dp[u][1](正方向根到当前点的第二大值),记录最大值的父亲节点。
反方向遍历一遍,求dp[u][2](代表反方向根到当前节点的最大值)
找出两个方向最大一个输出。
#include<algorithm>
#include<string.h>
#include<stdio.h>
#define M 10010
using namespace std;
struct path
{
int to,nextt,v;
} A[2*M];
int head[M],dp[M][3],re[M];
int tot,n,y,w;
void init()
{
tot=0;
memset(head,-1,sizeof(head));
memset(dp,0,sizeof(dp));
}
void add(int from,int to,int value)
{
A[tot].to=to;
A[tot].v=value;
A[tot].nextt=head[from];
head[from]=tot++;
}
int dfs1(int u,int fa)
{
int tem,sum;
if(dp[u][0]>0) return dp[u][0];
for(int i=head[u]; i!=-1; i=A[i].nextt)
{
tem=A[i].to;
if(fa==i) continue;
sum=dfs1(tem,i^1);
if(dp[u][0]<sum+A[i].v)
{
re[u]=tem;
dp[u][1]=max(dp[u][1],dp[u][0]);
dp[u][0]=sum+A[i].v;
}
else if(dp[u][1]<sum+A[i].v)//如果不大于最大权,大于次大权,也要换。
dp[u][1]=sum+A[i].v;
}
return dp[u][0];
}
int dfs2(int u,int fa)
{
int tem;
for(int i=head[u];i!=-1;i=A[i].nextt)
{
tem=A[i].to;
if(i==fa) continue;
if(tem==re[u]) dp[tem][2]=max(dp[u][2],dp[u][1])+A[i].v;
else dp[tem][2]=max(dp[u][2],dp[u][0])+A[i].v;
dfs2(tem,i^1);
}
return 0;
}
int main()
{
while(scanf("%d",&n)==1&&n)
{
init();
for(int i=2; i<=n; i++)
{
scanf("%d%d",&y,&w);
add(i,y,w);
add(y,i,w);
}
dfs1(1,-1);//正向求一遍
dfs2(1,-1);//反向求一遍
for(int i=1; i<=n; i++)
printf("%d\n",max(dp[i][0],dp[i][2]));
}
}