hdu2196 树形dp

时间:2022-05-17 01:47:48

题目链接:http://acm.split.hdu.edu.cn/showproblem.php?pid=2196

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. 
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

总算彻底理解这个题了 =.=

代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn=; struct Edge
{
int v;
int len;
int next;
} edge[maxn<<]; int head[maxn];
int fm[maxn],fn[maxn]; ///最远距离,以及对应的子树的序号
int sm[maxn],sn[maxn]; ///次远距离,以及其对应的子树
int k; void addedge(int u,int v,int l)
{
edge[k].v=v;
edge[k].len=l;
edge[k].next=head[u];
head[u]=k++; edge[k].v=u;
edge[k].len=l;
edge[k].next=head[v];
head[v]=k++;
} void dfs1(int u,int p) ///第一次dfs找到子树种最大的长度,和最大长度的子树的序号
{
fm[u]=; ///初始化
sm[u]=;
for(int i=head[u]; i!=-; i=edge[i].next)
{
int v=edge[i].v;
if(v==p) continue;
dfs1(v,u);
if(edge[i].len+fm[v]>sm[u])
{
sm[u]=edge[i].len+fm[v];
sn[u]=v;
if(sm[u]>fm[u])
{
swap(fm[u],sm[u]);
swap(fn[u],sn[u]);
}
}
}
} void dfs2(int u,int p)
{
for(int i=head[u]; i!=-; i=edge[i].next)
{
int v=edge[i].v;
if(v==p) continue;
if(v==fn[u])
{
if(edge[i].len+sm[u]>sm[v])
{
sm[v]=edge[i].len+sm[u];
sn[v]=u; ///开始没懂为什么还要记录结点
if(sm[v]>fm[v]) ///更新的目的就是可以找到从子树来的最大值,不记录有时候找的是次大值
{
swap(fm[v],sm[v]);
swap(fn[v],sn[v]);
}
}
}
else
{
if(edge[i].len+fm[u]>sm[v])
{
sm[v]=edge[i].len+fm[u];
sn[v]=u;
if(sm[v]>fm[v])
{
swap(fm[v],sm[v]);
swap(fn[v],sn[v]);
}
}
}
dfs2(v,u);
}
} int main()
{
int n;
while(scanf("%d",&n)==)
{
memset(head,-,sizeof(head));
k=;
int x,l;
for(int i=; i<=n; i++)
{
scanf("%d%d",&x,&l);
addedge(i,x,l);
}
dfs1(,-); ///随便选一点作为树根,那么他的父亲结点就设为-1
dfs2(,-); ///所以换成dfs1(2,-1),dfs2(2,-1) 也是可以的
for(int i=; i<=n; i++)
printf("%d\n",fm[i]);
}
return ;
}