Computer
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 34146 Accepted Submission(s): 5285
Problem Description
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
解析:
树形DP+二次扫描+换根法。
题意就是求树中距离每个点最长的距离,算是树形DP中一个经典的题型了。
令分别表示以为根的子树中距离最长及次长的路径长以及的反向最大距离(即往父节点走的路径的最大值)。
前两个值可以通过一遍DFS求得,反向最大距离需要再次DFS,分两种情况进行讨论:
1.在的最长路径上,则
2.否则
答案即为
代码:
#include <bits/stdc++.h>
using namespace std;
const int Max=20005;
int n,m,size;
int first[Max],d[Max][3],son[Max];
struct shu{int to,next,len;};
shu edge[Max<<1];
inline int get_int()
{
int x=0,f=1;
char c;
for(c=getchar();(!isdigit(c))&&(c!='-');c=getchar());
if(c=='-') f=-1,c=getchar();
for(;isdigit(c);c=getchar()) x=(x<<3)+(x<<1)+c-'0';
return x*f;
}
inline void pre()
{
size=0;
for(int i=1;i<=n;i++) first[i]=d[i][0]=d[i][1]=d[i][2]=0;
}
inline void build(int x,int y,int z)
{
edge[++size].next=first[x];
first[x]=size;
edge[size].to=y,edge[size].len=z;
}
inline void dfs1(int point,int fa)
{
for(int u=first[point];u;u=edge[u].next)
{
int to=edge[u].to,len=edge[u].len;
if(to==fa) continue;
dfs1(to,point);
if(d[point][1] < d[to][1]+len) son[point]=to,d[point][0]=d[point][1],d[point][1]=d[to][1]+len;
else d[point][0]=max(d[to][1]+len,d[point][0]);
}
}
inline void dfs2(int point,int fa)
{
for(int u=first[point];u;u=edge[u].next)
{
int to=edge[u].to,len=edge[u].len;
if(to==fa) continue;
if(to==son[point]) d[to][2]=max(d[to][2],max(d[point][0]+len,d[point][2]+len));
else d[to][2]=max(d[to][1],max(d[point][1]+len,d[point][2]+len));
dfs2(to,point);
}
}
int main()
{
while(~scanf("%d",&n))
{
pre();
for(int i=2;i<=n;i++)
{
int x=get_int(),y=get_int();
build(i,x,y),build(x,i,y);
}
dfs1(1,0);
dfs2(1,0);
for(int i=1;i<=n;i++) cout<<max(d[i][1],d[i][2])<<"\n";
}
return 0;
}