voiddfs(int u){ for (auto v : son[u]) { dfs(v); for (int j = min(m, sum[u] + sum[v]); j >= 0; --j) for (int k = max(j - sum[u], 0); k <= min(j, sum[v]); ++k) f[u][j] = max(f[u][j], f[u][j - k] + f[v][k]); sum[u] += sum[v]; } if (u) { sum[u]++; for (int j = min(m, sum[u]); j; --j) f[u][j] = f[u][j - 1] + w[u]; } }
intmain(){ n = rd(); m =rd(); for (int i = 1; i <= n; ++i) { son[rd()].push_back(i); w[i] = rd(); } dfs(0); int ans = 0; for (int i = 1; i <= m; ++i) ans = max(ans, f[0][i]); printf("%d\n", ans); return0; }
voidadd(int u, int v, int w){ e[++tot].to = v; e[tot].w = w; e[tot].nxt = hd[u]; hd[u] = tot; }
voiddfs(int u, int fa, int w){ for (int i = hd[u], v; i; i = e[i].nxt) { if ((v = e[i].to) != fa) { dfs(v, u, e[i].w); for (int j = min(Q, sum[u] + sum[v]); j >= 0; --j) for (int k = max(j - sum[u], 0); k <= min(j, sum[v]); ++k) f[u][j] = max(f[u][j], f[u][j - k] + f[v][k]); sum[u] += sum[v]; } } if (u) { sum[u]++; for (int j = min(Q, sum[u]); j; --j) f[u][j] = f[u][j - 1] + w; } }
intmain(){ n = rd(); Q = rd(); for (int i = 1; i < n; ++i) { int u = rd() - 1, v = rd() - 1, w = rd(); add(u, v, w); add(v, u, w); } dfs(0, 0, 0); int ans = 0; for (int i = 1; i <= Q; ++i) ans = max(ans, f[0][i]); printf("%d\n", ans); return0; }
voiddfs(int u){ for (auto v : son[u]) { dfs(v); for (int j = min(m, sum[u] + sum[v]); j >= 0; --j) for (int k = max(j - sum[u], 0); k <= min(j, sum[v]); ++k) { f[u][j][0] = max(f[u][j][0], f[u][j - k][0] + max(f[v][k][0], f[v][k][1])); f[u][j][1] = max(f[u][j][1], f[u][j - k][1] + f[v][k][0]); } sum[u] += sum[v]; } sum[u]++; for (int i = min(m, sum[u]); i; --i) f[u][i][1] = f[u][i - 1][1] + w[u]; }
intmain(){ n = rd(); m = rd(); for (int i = 2; i <= n; ++i) son[rd()].push_back(i); for (int i = 1; i <= n; ++i) w[i] = rd(); dfs(1); int ans = 0; for (int i = 1; i <= m; ++i) ans = max(ans, max(f[1][i][0], f[1][i][1])); printf("%d\n", ans); return0; }
Post title:树形背包
Post author:Eva.Q
Create time:2022-07-02 13:55:44
Post link:https://qyy/2022/07/02/Algorithm/knapsack-on-tree/
Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.