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;
    }
}

猜你喜欢

转载自blog.csdn.net/jkdd123456/article/details/81123286