3 2 0 1 0 2 0 3 7 4 2 2 0 1 0 4 2 1 7 1 7 6 2 2 0 0
5 13
树形dp入门题,设dp[i][j]表示以i为根然后攻克j个城堡所能获得的最大财富
#include <map> #include <set> #include <list> #include <stack> #include <queue> #include <vector> #include <cmath> #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; int dp[210][210]; struct node { int next; int to; }edge[210 * 210]; int head[210]; int w[210]; int tot, n, m; void addedge(int from, int to) { edge[tot].to = to; edge[tot].next = head[from]; head[from] = tot++; } void dfs(int u, int cnt) { dp[u][1] = w[u]; for (int i = head[u]; ~i; i = edge[i].next) { int v = edge[i].to; if(cnt > 1) { dfs(v, cnt - 1); } for (int j = cnt; j >= 1; j--) { for (int k = 0; k < j; k++) { dp[u][j] = max(dp[u][j], dp[v][k] + dp[u][j - k]); } } } } int main() { int u; while (~scanf("%d%d", &n, &m)) { if (!n && !m) { break; } memset ( dp, 0, sizeof(dp) ); memset ( head, -1, sizeof(head) ); tot = 0; w[0] = 0; for (int i = 1; i <= n; i++) { scanf("%d%d", &u, &w[i]); addedge(u, i); } dfs(0, m + 1); printf("%d\n", dp[0][m + 1]); } return 0; }