Computer
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2850 Accepted Submission(s): 1450
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.
/***
分析:以編號的i的節點爲例(非根節點),最長的路徑長度只有倆種可能,
1)子樹中存在最長路徑;
2)通過父節點的路徑中存在最長路徑
所以,只有分別求出每一節點對應的那倆種路徑取大最大值即可,其中,根節點只存在第一種可能
***/
#include "stdio.h"
#include "string.h"
#define N 10005
struct node{
int x,y;
int weight;
int next;
}edge[4*N];
int idx,head[N];
void Init(){idx=0; memset(head,-1,sizeof(head));}
void Add(int x,int y,int weight)
{
edge[idx].x = x;
edge[idx].y = y;
edge[idx].weight = weight;
edge[idx].next = head[x];
head[x] = idx++;
}
struct point{
int id;
int value;
}dp1[N],dp2[N]; //dp1[i]記錄點i的最遠距離,dp2[i]記錄點i的次遠距離,
void swap(point &a,point &b)
{
point c;
c = a;
a = b;
b = c;
}
void DFS1(int x,int father)
{
int i,y;
dp1[x].value = dp2[x].value = 0;
for(i=head[x]; i!=-1; i=edge[i].next)
{
y = edge[i].y;
if(y==father) continue;
DFS1(y,x);
if(dp1[y].value + edge[i].weight > dp2[x].value)
{
dp2[x].value = dp1[y].value + edge[i].weight;
dp2[x].id = y;
if(dp1[x].value < dp2[x].value) //dp1[i]記錄點i的最遠距離,dp2[i]記錄點i的次遠距離,
swap(dp1[x],dp2[x]);
}
}
}
void DFS2(int x,int father)
{
int i,y;
for(i=head[x]; i!=-1; i=edge[i].next)
{
y = edge[i].y;
if(y==father) continue;
if(dp1[x].id == y) //點y是父親x的最遠距離的下一個節點
{
if(dp2[y].value < dp2[x].value+edge[i].weight) //,那麼看點y的次元距離能否通過父親x的其他節點更新
{
dp2[y].value = dp2[x].value + edge[i].weight;
dp2[y].id = x;
if(dp1[y].value < dp2[y].value)
swap(dp1[y],dp2[y]);
}
}
else
{
if(dp2[y].value < dp1[x].value+edge[i].weight)
{
dp2[y].value = dp1[x].value+edge[i].weight;
dp2[y].id = x;
if(dp1[y].value < dp2[y].value)
swap(dp1[y],dp2[y]);
}
}
DFS2(y,x);
}
}
int main()
{
int i,n;
int x,y,k;
while(scanf("%d",&n)!=EOF)
{
Init();
for(y=2; y<=n; ++y)
{
scanf("%d %d",&x,&k);
Add(x,y,k);
Add(y,x,k);
}
DFS1(1,-1);
DFS2(1,-1);
for(i=1; i<=n; ++i)
printf("%d\n",dp1[i].value);
}
return 0;
}