一道树形DP
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 using namespace std; 5 int n,m; 6 int f[301][301];//f[i][j]表示由根节点i选j门课的最大学分 7 8 struct TREE 9 { 10 int l,r,val; 11 }tree[301]; 12 13 int dfs(int root,int num) 14 { 15 if (root<0||num==0) 16 return 0; 17 if (root==0) 18 return dfs(tree[root].l,num); 19 if (f[root][num]!=0) 20 return f[root][num]; 21 f[root][num]=dfs(tree[root].r,num); 22 for (int i=0;i<=num-1;i++) 23 f[root][num]=max(f[root][num],dfs(tree[root].l,i)+tree[root].val+dfs(tree[root].r,num-1-i)); 24 return f[root][num]; 25 } 26 27 int main() 28 { 29 memset(tree,-1,sizeof(tree)); 30 memset(f,0,sizeof(f)); 31 scanf("%d%d",&n,&m); 32 for (int i=1;i<=n;i++) 33 { 34 int pre,s; 35 scanf("%d%d",&pre,&s); 36 tree[i].r=tree[pre].l,tree[i].val=s; 37 tree[pre].l=i; 38 } 39 tree[0].val=0; 40 printf("%d ",dfs(0,m)); 41 return 0; 42 }