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
| #include <bits/stdc++.h> using namespace std; const int N = 301, M = 302; int u, v, h[N], e[N], ne[N], idx; int n, m; int dp[N][M]; void add(int u, int v) { e[++idx] = v, ne[idx] = h[u], h[u] = idx; } int dfs(int u) { int sum = 2; for (int i = h[u]; i; i = ne[i]) { int v = e[i]; int s = dfs(v); sum += s; for (int j = min(m, sum); j; --j) for (int k = 0; k < min(j, s); ++k) dp[u][j] = max(dp[u][j], dp[v][k] + dp[u][j - k]); } return sum; } int main() { scanf("%d%d", &n, &m); ++m; for (int i = 1; i <= n; ++i) { scanf("%d%d", &u, &dp[i][1]); add(u, i); } dfs(0); printf("%d\n", dp[0][m]); return 0; }
|