The more, The Better
Time Limit: 6000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 3935 Accepted Submission(s): 2312
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
思路:树形依赖背包,用dfs。题目给出的是一个森林,我们可以加上结点0作为根,使森林变为一棵树,然后就是树DP了。
AC代码:
#include <cstring>
#include <string>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cmath>
#include <vector>
#include <cstdlib>
#include <iostream>
#define max2(a,b) ((a) > (b) ? (a) : (b))
#define min2(a,b) ((a) < (b) ? (a) : (b))
using namespace std;
vector<int>r[205];
int dp[205][205],w[205];
bool vis[205];
int n,m;
void dfs(int x)
{
vis[x]=true;
dp[x][1]=w[x];
for(int i=0;i<(int)r[x].size();i++)
{
int t=r[x][i];
if(vis[t]) continue;
dfs(t);
for(int j=m;j>=1;j--)
for(int k=1;k<=j-1;k++)
{
dp[x][j]=max2(dp[x][j],dp[x][j-k]+dp[t][k]);
}
}
}
int main()
{
int a;
while(cin>>n>>m,n||m)
{
for(int i=0;i<=n;i++)
r[i].clear();
for(int i=1;i<=n;i++)
{
cin>>a>>w[i];
r[a].push_back(i);
}
memset(dp,0,sizeof(dp));
memset(vis,false,sizeof(vis));
m++; //注意,加上0结点后要+1
dfs(0);
if(m==0)
cout<<0<<endl;
else
cout<<dp[0][m]<<endl;
}
return 0;
}