The question is that there are n rooms to form a tree. You have m soldiers. Starting from Room 1, the soldiers start to depart from the adjacent room. Each room has a price, the price is/20 soldiers,
At the same time, there is a value, asking you how much value the M soldiers can get.
When DP [I] [J] is defined to indicate that the root node is I, the maximum possible obtained by J soldiers is used.
DP [I] [J] = max (DP [I] [J], DP [I] [J-K] + dp [son [I] [k]);
#include <cstdio>#include <cstring>#include <algorithm>#include <vector>using namespace std;vector <int> g[120];int n,m;int dp[120][120];int num[120],val[120];void dfs(int u,int fa){ int i,j,k; int v; for(i=num[u];i<=m;i++) dp[u][i]=val[u]; for(i=0;i<g[u].size();i++) { v=g[u][i]; if(v==fa) continue; dfs(v,u); for(j=m;j>=num[u];j--) for(k=1;k<=j-num[u];k++) dp[u][j]=max(dp[u][j],dp[u][j-k]+dp[v][k]); }}int main(){ while(scanf("%d%d",&n,&m),n!=-1&&m!=-1) { int i,j,x,y; for(i=1;i<=n;i++) { scanf("%d%d",&x,&y); x=(x+19)/20; num[i]=x; val[i]=y; } memset(dp,0,sizeof(dp)); for(i=1;i<=n;i++) g[i].clear(); for(i=1;i<n;i++) { scanf("%d%d",&x,&y); g[x].push_back(y); g[y].push_back(x); } if(m==0) {printf("0\n");continue;} dfs(1,-1); printf("%d\n",dp[1][m]); } return 0;}
HDU 1011 Starship Troopers tree DP