HDU Starship Troopers(树形DP)

题目链接: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;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值