hdu 1561The more, The Better(树上背包+对树分别背包)
时间:2021-02-26 12:53:14
收藏:0
阅读:0
The more, The Better
Time Limit: 6000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 12033 Accepted Submission(s): 6978
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
思路:给了我们每一个点的前驱,而且最多只有一个,也就是只有一个父节点,所以最终的图是有许多树构成的,前驱为0的点就是树的根,我们在每棵树上进行背包,然后再把所有树进行一次背包,相当于存在一个虚拟节点就是所有树根节点的父节点,在该虚拟节点上进行dp
代码:
#include<iostream> #include<string> #include<stack> #include<queue> #include<string.h> #include<map> #include<unordered_map> #include<vector> #include<cmath> #include<iostream> #include<algorithm> using namespace std; typedef long long ll; const int maxn = 205; const int maxm = 500; #define lson rt<<1,l,mid #define rson rt<<1|1,mid+1,r inline int read() { int f = 1, num = 0; char ch = getchar(); while (0 == isdigit(ch)) { if (ch == ‘-‘)f = -1; ch = getchar(); } while (0 != isdigit(ch)) num = (num << 1) + (num << 3) + ch - ‘0‘, ch = getchar(); return num * f; } struct edge { int to, nxt; }e[maxm]; int hd[maxn], tot; void add(int f, int t) { e[++tot].to = t; e[tot].nxt = hd[f]; hd[f] = tot; } int n, m; bool st[maxn]; int dp[maxn][maxn],sp[maxn]; int val[maxn]; void dfs(int u, int last) { if (last == 0)return; for (int i = 1; i <= last; i++)dp[u][i] = val[u]; for (int i = hd[u]; i; i = e[i].nxt) { int v = e[i].to; dfs(v, last - 1); for (int i = last; i >= 1; i--) { for (int j = 1; j<= i-1; j++) { dp[u][i] = max(dp[u][i], dp[u][i - j] + dp[v][j]); } } } } int main() { //freopen("test.txt", "r", stdin); while (scanf("%d%d", &n, &m) && n) { memset(hd, 0, sizeof(hd)); memset(st, 0, sizeof(st)); memset(sp, 0, sizeof(sp)); memset(dp, 0, sizeof(dp)); tot = 0; for (int i = 1; i <= n; i++) { int a = read(), b = read(); val[i] = b; if (a == 0) st[i] = 1; else { add(a, i); } } for (int i = 1; i <= n; i++) { if (st[i]) {//对没棵树进行树上背包 dfs(i,m); } } for (int i = 1; i <= n; i++) {//最后对每颗树做松弛操作 if (st[i]) { for (int s = m; s >= 1; s--) { for (int j = 1; j<= s; j++) { sp[s] = max(sp[s], sp[s - j] + dp[i][j]); } } } } cout << sp[m] << endl; } return 0; }
评论(0)