HDU - 2196 Computer 树形dp 两边dfs 典型

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   

题意:给出一颗树,求树中的每个顶点到其他所有顶点的最大值。

题解:一个节点的最大距离有两种情况:

1. 到子节点的最大距离

2.父节点的最大距离(除了该节点分支)+ 根节点到该节点的距离

所以我们两边dfs 即可解决

第一遍,我们记录下每个节点到子节点的最大距离和次大距离,并记录最大距离的子代

第二遍,更新每个节点经过父节点这个路径的最大距离

最后输出,经过父节点最大距离和到子节点最大距离较大一个即可

#include<iostream>
#include<cstdio>
#include<vector>
#include<cstring>
using namespace std;
const int N=1e4+10;
vector<int> v[N];
int n,lm[N],head[N],dp[N][3],len;
struct node{
	int to,d,nex;
}e[N*2];
void add(int x,int y,int d)
{
	e[len].to=y;
	e[len].d=d;
	e[len].nex=head[x];
	head[x]=len++;
}
int dfs(int f,int u)
{
	dp[u][0]=dp[u][1]=dp[u][2]=0;
	for(int i=head[u];i!=-1;i=e[i].nex)
	{
		int to=e[i].to;
		if(to==f) continue;
		int dis=dfs(u,to)+e[i].d;
	//	cout<<dis<<endl;
		if(dis>dp[u][0]) dp[u][1]=dp[u][0],dp[u][0]=dis,lm[u]=to;
		else if(dis>dp[u][1]) dp[u][1]=dis;
	}
//	cout<<u<<" "<<dp[u][0]<<" "<<dp[u][1]<<endl;
	return dp[u][0];
}
void dfs2(int f,int u)
{
	for(int i=head[u];i!=-1;i=e[i].nex)
	{
		int to=e[i].to;
		if(to==f) continue;
		if(to==lm[u]) dp[to][2]=max(dp[u][1],dp[u][2])+e[i].d;
		else dp[to][2]=max(dp[u][0],dp[u][2])+e[i].d;
//		cout<<to<<" "<<dp[to][2]<<endl;
		dfs2(u,to);
	}
}
int main()
{
	int u,d;
	while(~scanf("%d",&n))
	{
		memset(head,-1,sizeof(head));
		len=0;
		memset(lm,-1,sizeof(lm));
		for(int i=2;i<=n;i++)
		{
			scanf("%d%d",&u,&d);
			add(u,i,d);
			add(i,u,d);	
		}
		dfs(0,1);
		dfs2(0,1);
		for(int i=1;i<=n;i++)
			printf("%d\n",max(dp[i][0],dp[i][2]));
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/mmk27_word/article/details/85085874