#include <iostream>
#include <vector>
using namespace std;
vector<int> g[200005];
int f[200005][505], a[200005], k;
void dfs(int x) {
for (int w : g[x]) {
dfs(w);
for (int i = k; i >= 0; i--) {
for (int j = 0; j <= k - i; j++) {
if (j != 0 && f[w][j] == 0) break;
f[x][i + j] = max(f[x][i + j], f[x][i] + f[w][j]);
}
}
}
f[x][1] = max(f[x][1], a[x]);
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int n, r = 0;
cin >> n >> k;
for (int i = 1; i <= n; i++) {
int x, y;
cin >> x >> y;
a[i] = y;
if (x == 0) {
r = i;
}
else {
g[x].push_back(i);
}
}
dfs(r);
cout << f[r][k];
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
7000 KB |
Output is correct |
2 |
Correct |
2 ms |
7016 KB |
Output is correct |
3 |
Correct |
2 ms |
7260 KB |
Output is correct |
4 |
Correct |
19 ms |
24716 KB |
Output is correct |
5 |
Correct |
22 ms |
26964 KB |
Output is correct |
6 |
Correct |
30 ms |
26956 KB |
Output is correct |
7 |
Correct |
321 ms |
301524 KB |
Output is correct |
8 |
Correct |
315 ms |
301820 KB |
Output is correct |
9 |
Correct |
456 ms |
366280 KB |
Output is correct |
10 |
Correct |
513 ms |
403664 KB |
Output is correct |