HDU - 1561 CH5402 有依赖性背包 树形背包

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

题意:每个节点都有一个价值,取儿子节点必须取父亲节点,让从n个取m个节点,价值最大

思路:题目给的是森林,可以让0为总根,建立一颗n+1个节点的树,但是要注意0节点的特殊

DP[i][j]表示以i为根节点的子树,取j个的最大价值(树形dp的一般套路 )

DP[u][j]=max(DP[v][j-k]+DP[u][k])父亲节点取 j个    儿子节点取j-k个+父亲节点取k个,而且j必须要从大到小,保证DP[u][k]没有更新过

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include<vector>
#include<set>
#include<queue>
#include<algorithm>
#include<stack>
#include<cstdlib>
#include<deque>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll,int>P;
const int len=1e3+5;
const ll mod=2147483648;
const double pi=acos(-1.0);
int head[len],nex[len],ver[len];
int dp[len][len];
int a[len];
int n,m,tot;
void add(int u,int v)
{
	tot++;
	ver[tot]=v;
	nex[tot]=head[u];
	head[u]=tot;
}
void dfs(int u)
{
	for(int i=head[u];i;i=nex[i])
	{
		int v=ver[i];
		dfs(v);
		for(int j=m;j>=0;--j)
			for(int k=j;k>=0;--k)
				dp[u][j]=max(dp[u][j],dp[v][j-k]+dp[u][k]);
	}
	if(u!=0)
		for(int i=m;i>=1;--i)
			dp[u][i]=dp[u][i-1]+a[u];
}
int main()
{	
	while(scanf("%d%d",&n,&m)&&n+m)
	{
		tot=0;
		memset(dp,0,sizeof(dp));
		memset(head,0,sizeof(head));
		for(int i=1;i<=n;++i)
		{
			int v=i,u;
			scanf("%d%d",&u,&a[i]);
			add(u,v);
		}
		dfs(0);
		printf("%d\n",dp[0][m]);
	}
}

猜你喜欢

转载自blog.csdn.net/hutwuguangrong/article/details/86660472