The more, The Better
Time Limit: 6000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5472 Accepted Submission(s): 3251
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
HDU 2006-12 Programming Contest
Recommend
LL | We have carefully selected several similar problems for you: 1011 2159 2639 1203 1712
树形dp入门题,设dp[i][j]表示以i为根然后攻克j个城堡所能获得的最大财富
#include <map>
#include <set>
#include <list>
#include <stack>
#include <queue>
#include <vector>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
int dp[210][210];
struct node
{
int next;
int to;
}edge[210 * 210];
int head[210];
int w[210];
int tot, n, m;
void addedge(int from, int to)
{
edge[tot].to = to;
edge[tot].next = head[from];
head[from] = tot++;
}
void dfs(int u, int cnt)
{
dp[u][1] = w[u];
for (int i = head[u]; ~i; i = edge[i].next)
{
int v = edge[i].to;
if(cnt > 1)
{
dfs(v, cnt - 1);
}
for (int j = cnt; j >= 1; j--)
{
for (int k = 0; k < j; k++)
{
dp[u][j] = max(dp[u][j], dp[v][k] + dp[u][j - k]);
}
}
}
}
int main()
{
int u;
while (~scanf("%d%d", &n, &m))
{
if (!n && !m)
{
break;
}
memset ( dp, 0, sizeof(dp) );
memset ( head, -1, sizeof(head) );
tot = 0;
w[0] = 0;
for (int i = 1; i <= n; i++)
{
scanf("%d%d", &u, &w[i]);
addedge(u, i);
}
dfs(0, m + 1);
printf("%d\n", dp[0][m + 1]);
}
return 0;
}