树形分组背包
注意顺序
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
using namespace std;
const int MAXN = 305;
vector <int> g[MAXN];
int dp[MAXN][MAXN], num[MAXN], fa[MAXN], rot, n, m;
void dfs(int u) {
for(int i = 0; i < g[u].size(); i++) {
int v = g[u][i];
dfs(v);
for(int j = m; j >= 0; j--) {
for(int k = 0; k <= j; k++) {
dp[u][j] = max(dp[u][j], dp[u][j - k] + dp[v][k]);
}
}
}
if(u) {
for(int i = m; i >= 1; i--) {
dp[u][i] = dp[u][i - 1] + num[u];
}
}
}
int main() {
cin >> n >> m;
for(int i = 1; i <= n; i++) {
cin >> fa[i] >> num[i];
g[fa[i]].push_back(i);
}
dfs(0);
cout << dp[0][m] << endl;
return 0;
}