题意就不多解释了,毕竟中文题
思路我也是参考的别人的代码,因为这道题结合了01背包的思想,一开始没有想到
#include <stdio.h> #include <string.h> #include <algorithm> using namespace std; struct node { int from,to,next; } tree[205]; int vis[205],dp[205][205],ans[205][205],head[205],mat[205]; int len,n,m; void add(int a,int b) { tree[len].from = a; tree[len].to = b; tree[len].next = head[a]; head[a] = len++; } void dfs(int root) { int i,j,k,tem; vis[root] = 1; for(i = head[root]; i!=-1; i = tree[i].next) { tem = tree[i].to; if(!vis[tem]) { dfs(tem); for(k = m; k>=0; k--)//01背包 { for(j = 0; j<=k; j++) ans[root][k] = max(ans[root][k],ans[root][k-j]+dp[tem][j]); } } } for(j = 1; j<=m+1; j++) dp[root][j] = ans[root][j-1]+mat[root]; } int main() { int i,a,b; while(~scanf("%d%d",&n,&m),n+m) { len = 0; memset(head,-1,sizeof(head)); for(i = 1; i<=n; i++) { scanf("%d%d",&a,&b); mat[i] = b; add(a,i); } mat[0] = 0; memset(vis,0,sizeof(vis)); memset(dp,0,sizeof(dp)); memset(ans,0,sizeof(ans)); dfs(0); printf("%d\n",dp[0][m+1]); } return 0; }