hdu1561-The more, The Better

The more, The Better

Time Limit: 6000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 9397    Accepted Submission(s): 5463


Problem Description
ACboy很喜欢玩一种战略游戏,在一个地图上,有N座城堡,每座城堡都有一定的宝物,在每次游戏中ACboy允许攻克M个城堡并获得里面的宝物。但由于地理位置原因,有些城堡不能直接攻克,要攻克这些城堡必须先攻克其他某一个特定的城堡。你能帮ACboy算出要获得尽量多的宝物应该攻克哪M个城堡吗?
 

Input
每个测试实例首先包括2个整数,N,M.(1 <= M <= N <= 200);在接下来的N行里,每行包括2个整数,a,b. 在第 i 行,a 代表要攻克第 i 个城堡必须先攻克第 a 个城堡,如果 a = 0 则代表可以直接攻克第 i 个城堡。b 代表第 i 个城堡的宝物数量, b >= 0。当N = 0, M = 0输入结束。
 

Output
对于每个测试实例,输出一个整数,代表ACboy攻克M个城堡所获得的最多宝物的数量。
 

Sample Input
 
 
3 2 0 1 0 2 0 3 7 4 2 2 0 1 0 4 2 1 7 1 7 6 2 2 0 0
 

Sample Output
 
 
5 13
 

Author
8600
 

Source
 

Recommend

LL

题解:树形dp + 背包水题。

先设dp[x][i]为节点x及其子树取得i个城堡物品的最大值。

再设没有限制的点为根节点。因为根节点可能不止一个,所以在根节点上面再加一个节点,表示祖宗节点。对于每一个节点,要访问其直属子节点必须先访问它,故dp[x][1] = val[x];再对其子节点,求一遍背包即可。

AC代码

#include <stdio.h>
#include <iostream>
#include <string>
#include <queue>
#include <map>
#include <vector>
#include <algorithm>
#include <string.h>
#include <cmath>
 
using namespace std;

const int maxn = 222;
int dp[maxn][maxn];
vector<int> s[maxn];
int val[maxn];

void dfs(int x, int m){
	int len = s[x].size();
	dp[x][1] = val[x];
	for(int i = 0; i < len; i++)
		dfs(s[x][i], m);
	for(int i = 0; i < len; i++){
		int v = s[x][i];
		for(int j = m; j >= 2; j--)
			for(int k = j - 1; k >= 1; k--){
				dp[x][j] = max(dp[x][j], dp[x][k] + dp[v][j - k]);
			}
	}
}

int main(){
	int n, m, a, b;
	while(scanf("%d %d", &n, &m) && (n || m)){
		for(int i = 0; i <= n; i++){
			s[i].clear();
			for(int j = 0; j <= m + 1; j++)
				dp[i][j] = 0;
		}
		for(int i = 1; i <= n; i++){
			scanf("%d %d", &a, &val[i]);
			s[a].push_back(i);
		}
		val[0] = 0;
		dfs(0, m + 1);
		printf("%d\n", dp[0][m + 1]);
	}
	return 0;
} 
树形dp第三题,蒟蒻啊,想了好久。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值