HDU 1561 The more, The Better(树形DP)
和Vijos上的选课一模一样。。无奈效率700+,怎么这么慢啊。。。
1 #include <stdio.h> 2 #include <string.h> 3 #include <stdlib.h> 4 struct node 5 { 6 int left,right; 7 }tree[301]; 8 int p[301],dp[301][301]; 9 int max(int a,int b) 10 { 11 return a > b? a:b; 12 } 13 void insert(int son,int father) 14 { 15 int t; 16 if(!tree[father].left) 17 { 18 tree[father].left = son; 19 } 20 else 21 { 22 t = tree[father].left; 23 while(tree[t].right) 24 { 25 t = tree[t].right; 26 } 27 tree[t].right = son; 28 } 29 } 30 int dfs(int x,int y) 31 { 32 int i; 33 if(dp[x][y] > 0) 34 return dp[x][y]; 35 if(x == 0||y == 0) 36 return 0; 37 dp[x][y] = dfs(tree[x].right,y); 38 for(i = 0;i <= y-1;i ++) 39 { 40 dp[x][y] = max(dp[x][y],dfs(tree[x].left,i)+dfs(tree[x].right,y-1-i)+p[x]); 41 } 42 return dp[x][y]; 43 } 44 int main() 45 { 46 int n,m,i,a; 47 while(scanf("%d%d",&n,&m)!=EOF) 48 { 49 if(!n&&!m) break; 50 memset(tree,0,sizeof(tree)); 51 memset(dp,0,sizeof(dp)); 52 for(i = 1;i <= n;i ++) 53 { 54 scanf("%d%d",&a,&p[i]); 55 insert(i,a); 56 } 57 printf("%d\n",dfs(tree[0].left,m)); 58 } 59 return 0; 60 }