标签:== efi freopen algorithm col desc set 其他 树根
Time Limit: 6000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 12033 Accepted Submission(s): 6978
#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; }
hdu 1561The more, The Better(树上背包+对树分别背包)
标签:== efi freopen algorithm col desc set 其他 树根
原文地址:https://www.cnblogs.com/MYMYACMer/p/14445995.html