hdu1059 Dividing(多重背包+二进制优化)

花了也有一段时间理解背包模板和二进制转化,既然普通法做多重背包容易超时,不妨每个都用二进制优化。二进制优化按照2的次幂分堆,每次处理一堆,但因为用while每次乘2是跑完背包乘的,所以需要再跑一次背包。再有就是学到位运算的乘2,感觉有点收获。

#include <stdio.h>
#include <math.h>
#include <algorithm>
#include <cmath>

using namespace std;

const int N = 100005;

int sum;
int dp[N];

void ZeroOnePack(int cost, int weight)
{
    for(int i = sum; i >= cost; i --)
        dp[i] = max(dp[i], dp[i - cost] + weight);
}

void CompletePack(int cost, int weight)
{
    for(int i = cost; i <= sum; i ++)
        dp[i] = max(dp[i], dp[i - cost] + weight);
}

void MulPack(int cost, int weight, int countt)
{
    if(cost * countt >= sum) //如果背包能满
    {
        CompletePack(cost, weight);
        return;
    }
    int i = 1;
    while(i < countt)
    {
        ZeroOnePack(i * cost, i * weight);
        countt -= i;
        i <<= 1;
    }
    ZeroOnePack(countt * cost, countt * weight);
}

int main()
{
  //  freopen("in.txt", "r", stdin);
    int a[N], Case = 1;
    while(1)
    {
        sum = 0;
        for(int i = 1; i <= 6; i ++)
        {
            scanf("%d", &a[i]);
            sum += (a[i] * i);
        }
        if(!sum) break;
        printf("Collection #%d:\n", Case ++);
        if(sum % 2 == 1) printf("Can't be divided.\n\n");
        else
        {
            sum /= 2;
            for(int i = 0; i <= sum; i ++) dp[i] = 0;
            for(int i = 1; i <= 6; i ++)
            {
                if(a[i]) MulPack(i, i, a[i]);
            }
            if(dp[sum] == sum) printf("Can be divided.\n\n");
            else printf("Can't be divided.\n\n");
        }
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值