HDU P2196 Computer
题目
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
Author
scnu
题目大意
给出一个数
n
,表示树的大小,然后给出
然后,算出树中各点到离其最远的点的距离
多组数据
题解
树形
f[i][0]
表示以
i
为根的子树时,
f[i][1]
表示以
fa[i]
为根的树删去以
i
为根的子树时,
显然,对于节点
i
离它最远的点的距离即为
然后,就是转移方程了
对于 f[i][0] 有 f[i][0]=max(f[i][0],f[son[i]][0]+e[i,son[i]])
对于
f[i][1]
有
f[i][1]=max(f[i][1],t[fa[i]]+e[fa[i],i])
,其中
t[fa[i]]
为不经过
i
的离
代码
#include<cstdio>
#include<cstring>
using namespace std;
int n,tot;
int lnk[10005],f[10005][2];
struct edge
{
int nxt,y,v;
} e[20005];
int readln()
{
int x=0;
char ch=getchar();
while (ch<'0'||ch>'9') ch=getchar();
while ('0'<=ch&&ch<='9') x=x*10+ch-48,ch=getchar();
return x;
}
void add(int x,int y,int v)
{
tot++;e[tot].nxt=lnk[x];lnk[x]=tot;e[tot].y=y;e[tot].v=v;
}
int max(int x,int y){return x>y?x:y;}
void dfs1(int x,int fa)
{
int v,y;
for (int i=lnk[x];i;i=e[i].nxt)
{
y=e[i].y,v=e[i].v;
if (fa==y) continue;
dfs1(y,x);
f[x][0]=max(f[x][0],f[y][0]+v);
}
}
void dfs2(int x,int fa)
{
int t0=0,t1=0,p0=0,p1=0,v,y;
for (int i=lnk[x];i;i=e[i].nxt)
{
y=e[i].y,v=e[i].v;
if (fa==y) continue;
if (f[y][0]+v>t0) t1=t0,t0=f[y][0]+v,p1=p0,p0=y;
else if (f[y][0]+v>t1) t1=f[y][0]+v,p1=y;
}
for (int i=lnk[x];i;i=e[i].nxt)
{
y=e[i].y,v=e[i].v;
if (fa==y) continue;
f[y][1]=f[x][1]+v;
if (p0!=y) {
if (p0!=0) f[y][1]=max(f[y][1],t0+v);
} else
if (p1!=y)
{
if (p1!=0) f[y][1]=max(f[y][1],t1+v);
}
dfs2(y,x);
}
}
int main()
{
while (~scanf("%d",&n))
{
memset(f,0,sizeof(f));
memset(lnk,0,sizeof(lnk));
tot=0;
int x,y;
for (int i=2;i<=n;i++)
{
x=readln(),y=readln();
add(i,x,y);add(x,i,y);
}
dfs1(1,0);
dfs2(1,0);
for (int i=1;i<=n;i++) printf("%d\n",max(f[i][0],f[i][1]));
}
return 0;
}