Coins(多重背包转化为01+完全背包)

Whuacmers use coins.They have coins of value A1,A2,A3…An Silverland dollar. One day Hibix opened purse and found there were some coins. He decided to buy a very nice watch in a nearby shop. He wanted to pay the exact price(without change) and he known the price would not more than m.But he didn’t know the exact price of the watch.

You are to write a program which reads n,m,A1,A2,A3…An and C1,C2,C3…Cn corresponding to the number of Tony’s coins of value A1,A2,A3…An then calculate how many prices(form 1 to m) Tony can pay use these coins.

Input

Output
For each test case output the answer on a single line.
Sample Input

3 10
1 2 4 2 1 1
2 5
1 4 2 1
0 0

Sample Output

8
4

题意:
给你n种硬币的数量 c[i] 和价值 a[i] ,让你求组成小于等于m钱数的组成方案数;
属于有限次使用,多重背包问题,可以直接套用模板
满足某些条件的情况下,可以转化成 01背包和完全背包

AC code:

#include<cstdio>
#include<cmath>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long LL;
LL dp[100000+10]; //存储最后背包最大能存多少
LL a[100000+10];//存的是物品的价值,或者是重量
LL c[100000+10];//存的是数量
LL m;
void ZeroonePack(LL weight,LL value) // 01背包
{
    for(LL i=m;i>=weight;i--)
        dp[i]=max(dp[i],dp[i-weight]+value);
}
void completePack(LL weight,LL value) //完全背包  
{
    for(LL i=weight;i<=m;i++)
        dp[i]=max(dp[i],dp[i-weight]+value);
}
void MultiplePack(LL w,LL v,LL num) //多重背包
{
    if(num*w>=m){//如果总容量比这个物品的容量要小,那么这个物品可以直到取完,相当于完全背包
        completePack(w,v);
        return ;
    }
    LL k=1; //否则就将多重背包转化为01背包
    while(k<=num){
        ZeroonePack(k*w,k*v);
        num=num-k;
        k=k*2; //这里采用二进制思想
    }
    ZeroonePack(num*w,num*v);
}
int main()
{
    LL n;
    while(scanf("%lld %lld",&n,&m)!=EOF)
    {
        if(n==0&&m==0)
            break;
        for(LL i=0;i<n;i++){
            scanf("%lld",&c[i]);//输入价值  此题没有物品的重量,可以理解为体积和价值相等
        }
        for(LL i=0;i<n;i++)
            scanf("%lld",&a[i]);
        memset(dp,0,sizeof(dp));
        for(LL i=0;i<n;i++)
            MultiplePack(c[i],c[i],a[i]);//调用多重背包,注意穿参的时候分别是重量,价值和数量
        LL ans=0;
        for(LL i=1;i<=m;i++)
            if(dp[i]==i)
                ans++;
        cout<<ans<<endl;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值