-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTreeKnapsackOptimized.cpp
More file actions
47 lines (47 loc) · 1.06 KB
/
TreeKnapsackOptimized.cpp
File metadata and controls
47 lines (47 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// 树上背包(后序遍历优化),时间复杂度O(nm)
// https://loj.ac/p/160
#include <bits/stdc++.h>
using namespace std;
const int N = 50003;
const int M = 60003;
int n, m, tot;
int w[N], v[N], s[N], dfn[N], rdfn[N];
vector<vector<int>> g, f;
void dfs(int u) {
s[u] = 1;
for (int v : g[u]) {
dfs(v);
s[u] += s[v];
}
dfn[u] = ++tot; // 求后序遍历序
rdfn[tot] = u;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n >> m;
g.resize(n + 3);
f.resize(n + 3, vector<int>(m + 1));
for (int i = 1; i <= n; ++i) {
int d;
cin >> d;
g[d].push_back(i);
}
for (int i = 1; i <= n; ++i) {
cin >> w[i];
}
for (int i = 1; i <= n; ++i) {
cin >> v[i];
}
dfs(0);
for (int i = 1; i <= n + 1; ++i) {
for (int j = 0; j <= m; ++j) {
f[i][j] = f[i - s[rdfn[i]]][j]; // 不取当前节点,则其子树不能取
if (j >= w[rdfn[i]]) { // 取当前节点
f[i][j] = max(f[i][j], f[i - 1][j - w[rdfn[i]]] + v[rdfn[i]]);
}
}
}
cout << f[n + 1][m] << "\n";
return 0;
}