hdu2196 computer 树形dp

hdu2196

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.

  1. 最远距离等于反向最远与正向最远中的较大值取得。
  2. 正向最远由子节点正向最远加上到子节点的边权求得。
  3. 反向最远由父节点最远求得,其中可能是父节点正向最远,有可能是父节点反向最远。
  4. 父节点正向最远有可能通过正在确定答案的子节点,此时不应由这条正向最远更新答案。
  5. 4情况需要额外找一条正向次远来辅助确定答案。
#include <cstdio>
#include <cstring>
#define max(a, b) (a>b ? a:b)
#define min(a, b) (a<b ? a:b)
using namespace std;

const int N = 10101;
int dp[N][3], head[N], ver[N<<1], edge[N<<1], Next[N<<1], tot;

void init(){
	memset(Next, 0, sizeof(Next));
	memset(head, 0, sizeof(head));
	tot = 1;
}

void add(int x, int y, int z){
	ver[++tot] = y, edge[tot] = z, Next[tot] = head[x], head[x] = tot;
}

void dfs1(int x, int fa){
	int big1 = 0, big2 = 0;
	dp[x][1] = dp[x][0] = 0;
	for(int i = head[x]; i; i = Next[i]){
		int y = ver[i], z = edge[i];
		if(y==fa) continue;
		dfs1(y, x);
		if(dp[y][0] + z > big1) big2 = big1, big1 = dp[y][0] + z;
		else if(dp[y][0] + z > big2) big2 = dp[y][0] + z;
	}
	dp[x][0] = big1, dp[x][1] = big2;
}
void dfs2(int x, int fa){
	for(int i = head[x]; i; i = Next[i]){
		int y = ver[i], z = edge[i];
		if(y == fa) continue;
		//抖了个机灵大佬们不要喷我
		dp[y][2] = max(dp[x][2], dp[x][dp[y][0]+z==dp[x][0]]) + z;
		dfs2(y, x);
	}
}
int main(){
	int t;
	while(~scanf("%d", &t)){
		init();
		for(int i = 2; i <= t; i++){
			int x, y;
			scanf("%d%d", &x, &y);
			add(i, x, y);
			add(x, i, y);
		}
		dfs1(1, 0);
		dfs2(1, 0);
		for(int i = 1; i <= t; i++){
			printf("%d\n", max(dp[i][0], dp[i][2]));
		}
	}
	return 0;
}
//%zx
//%lrh
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值