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#include<stdio.h> #include<iostream> #include<vector> using namespace std; vector<int>map[305]; int dp[305][305],val[305],k[305],vist[305],N,M; int max(int a,int b) { return a>b?a:b; } void dfs(int p) { int flog=0; vist[p]=1; k[p]=1; for(int i=0;i<=N;i++) dp[p][i]=0; if(p) dp[p][1]=val[p],flog=1; for(int i=0;i<map[p].size();i++) { int son=map[p][i]; if(vist[son])continue ; dfs(son); k[p]+=k[son]; for(int m=k[p];m>=1;m--) for(int tk=1;tk<=k[son]&&tk<=m-flog;tk++) dp[p][m]=max(dp[p][m],dp[p][m-tk]+dp[son][tk]); } } int main() { int id; while(scanf("%d%d",&N,&M)>0) { if(N==0&&M==0) break; for(int i=0;i<=N;i++) map[i].clear(),vist[i]=0; for(int i=1;i<=N;i++) { scanf("%d%d",&id,&val[i]); map[id].push_back(i); } dfs(0); printf("%d\n",dp[0][M]); } }
HDU1561The more, The Better (树形DP),布布扣,bubuko.com
HDU1561The more, The Better (树形DP)
原文:http://blog.csdn.net/u010372095/article/details/21989029