HDU - 2196 Computer(经典树形DP)

题目链接:https://vjudge.net/problem/HDU-2196

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.

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


题意:求一个树中每个节点i(1<=i<=n)能到达的最远距离
思路:最远距离有两种可能:
(1)他到叶子结点的最远距离L1(dp[i][0]);
(2)(他的父节点到叶子结点的最远距离+父节点与它的距离)L2(dp[i][2]);
那么他的最远距离就是max(L1,L2);
用两次dfs,第一次dfs求出各个节点i能够到达的最远距离dp[i][0]和次远距离dp[i][1];
第二次dfs求出
dp[i][2];
AC代码:
#include<stdio.h>
#include<string.h>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn=10010;
int n,dp[maxn][3],vis[maxn];
struct node{
	int v,w;
	node(){}
	node(int _v,int _w){v=_v;w=_w;}
};
vector<node>a[maxn]; 
void dfs1(int u){
	vis[u]=1;
	for(int i=0;i<a[u].size();i++)
	{
		int v=a[u][i].v;
		int w=a[u][i].w;
		if(vis[v]) continue;
		dfs1(v);
		int sum=w+dp[v][0];
    	if(sum>dp[u][0])
		{
    		dp[u][1]=dp[u][0];
    		dp[u][0]=sum;
    	}
    	else if(sum>dp[u][1])
    	dp[u][1]=sum;
	}
}
void dfs2(int u){
	vis[u]=1;
	for(int i=0;i<a[u].size();i++){
		int v=a[u][i].v;
		int w=a[u][i].w;
		if(vis[v]) continue;
		dp[v][2]=max(dp[u][2],dp[v][0]+w==dp[u][0]?dp[u][1]:dp[u][0])+w;
		 //判断从父节点到叶子结点的最远距离是否经过当前点,若经过则取父节点的次大距离
        //最后加上父节点到当前点的距离即为当前点从父节点过来的最大距离
       dfs2(v); 
	}
}
int main()
{
	while(~scanf("%d",&n))
	{
		for(int i=0;i<maxn;i++) a[i].clear();	
		memset(dp,0,sizeof(dp));
		for(int i=2;i<=n;i++)
		{		
			int v,w;
			scanf("%d%d",&v,&w);
			a[i].push_back(node(v,w)); 
			a[v].push_back(node(i,w)); 
		}
		memset(vis,0,sizeof(vis));
		dfs1(1);
		memset(vis,0,sizeof(vis));
	    dfs2(1);
	    for(int i=1;i<=n;i++)
	    printf("%d\n",max(dp[i][0],dp[i][2]));
	}
 } 

posted @ 2018-09-06 20:55  ccsu_dj辉  阅读(101)  评论(0编辑  收藏  举报