【HDOJ】1561 The more, The Better
树状DP。
1 /* 1561 */ 2 #include <iostream> 3 #include <cstdio> 4 #include <cstring> 5 #include <cstdlib> 6 #include <algorithm> 7 #include <vector> 8 using namespace std; 9 10 #define MAXN 205 11 12 vector<int> tb[MAXN]; 13 int dp[MAXN][MAXN]; 14 int a[MAXN]; 15 int n, m; 16 17 int max(int a, int b) { 18 return a>b ? a:b; 19 } 20 21 void init() { 22 int i, j, k; 23 24 for (i=0; i<=n; ++i) 25 tb[i].clear(); 26 memset(dp, 0, sizeof(dp)); 27 } 28 29 void dfs(int u, int t) { 30 int i, j, k, tmp; 31 int v; 32 33 if (t <= 0) 34 return ; 35 36 for (i=0; i<tb[u].size(); ++i) { 37 v = tb[u][i]; 38 dfs(v, t-1); 39 for (j=t; j>=1; --j) { 40 for (k=1; k<=j; ++k) { 41 dp[u][j] = max(dp[u][j], dp[v][k]+dp[u][j-k]); 42 } 43 } 44 } 45 if (u) { 46 for (i=m; i>=1; --i) 47 dp[u][i] = dp[u][i-1] + a[u]; 48 } 49 } 50 51 int main() { 52 int i, j, k; 53 54 #ifndef ONLINE_JUDGE 55 freopen("data.in", "r", stdin); 56 #endif 57 58 a[0] = 0; 59 while (scanf("%d %d", &n, &m)!=EOF && (n||m)) { 60 for (i=1; i<=n; ++i) { 61 scanf("%d %d", &j, &a[i]); 62 tb[j].push_back(i); 63 } 64 dfs(0, m); 65 printf("%d\n", dp[0][m]); 66 init(); 67 } 68 69 return 0; 70 }