题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1011
这个题目是在树形DP的基础上在每个节点的一个分组背包问题
首先根据题目条件建立一颗树,然后DFS整棵树,每个节点的dp[i]
表示以这个节点为根,放i个士兵最多能得到brains的个数!
对每个非叶节点进行一次分组背包,最后输出根节点的dp[m]
#include <iostream>
#include <string.h>
#include <algorithm>
#include <stdio.h>
#include <vector>
using namespace std;
#define maxn 110
#define MAX(a,b) (a>b?a:b)
struct point{
vector<int> child;
int dp[maxn];
int v,c;
}po[maxn];
int n,m;
int tree_dp(int root){
if(po[root].child.empty()){
for(int i=po[root].v;i<=m;i++) po[root].dp[i]=po[root].c;
return 0;
}
for(int i=0;i<po[root].child.size();i++){
tree_dp(po[root].child[i]);
}
for(int i=po[root].v;i<=m;i++) po[root].dp[i]=po[root].c;
for(int i=0;i<po[root].child.size();i++){//分组背包,所有的分组,也就是每一个子节点为一组
for(int j=m;j>=po[root].v;j--)
for(int k=1;j+k<=m;k++){
po[root].dp[j+k]=MAX(po[root].dp[j+k],po[root].dp[j]+po[po[root].child[i]].dp[k]);
}
}
return 0;
}
int main(){
int i,j,k,a,b;
while(scanf("%d%d",&n,&m)){
if(n==-1 && m==-1) return 0;
for(i=0;i<=n;i++) po[i].child.clear();
memset(po,0,sizeof(po));
for(i=1;i<=n;i++){
scanf("%d%d",&po[i].v,&po[i].c);
po[i].v=(po[i].v+19)/20;
}
for(i=1;i<n;i++){
scanf("%d%d",&a,&b);
if(a<b) po[a].child.push_back(b);
else po[b].child.push_back(a);
}
if(m==0){
printf("0\n");continue;
}
tree_dp(1);
printf("%d\n",po[1].dp[m]);
}
return 0;
}