题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2844
题目描述:
Description
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
The input contains several test cases. The first line of each test case contains two integers n(1 ≤ n ≤ 100),m(m ≤ 100000).The second line contains 2n integers, denoting A1,A2,A3...An,C1,C2,C3...Cn (1 ≤ Ai ≤ 100000,1 ≤ Ci ≤ 1000). The last test case is followed by two zeros.
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种货币和最大钱数m,然后输入n种货币的单价,然后再输入n种货币的数目,叫你写出在不超过m的情况下,能组成几种数目的货币总和
就拿第一组来说,能组成1、2 、3、 4、 5、 6 、7 、8共八种
第二组能组成1、 2、 4 、5 、6(超过了5舍弃)共4种
题目解析:
由于种货币的数量不定,那么肯定是多重背包,但是这里如果直接转化成01背包的话肯定会超时,所以这里就需要用到二进制优化
我这里有个模板,遇到的一些一般性的多重背包问题可以直接套用:
多重背包模板:
int bag_01(int cost,int weight)//所占空间,价值
{
for(int i=m;i>=cost;i--)
dp[i]=max(dp[i],dp[i-cost]+weight);
}//01背包
int bag_cpt(int cost,int weight)//所占空间,价值
{
for(int i=cost;i<=m;i++)
dp[i]=max(dp[i],dp[i-cost]+weight);
}//完全背包
int bag_mul(int cost,int weight,int num)//所占空间,价值,数量
{
if(cost*num>=m)
{
bag_cpt(cost,weight);
return 1;
}
int k=1;
while(k<=num)
{
bag_01(k*cost,k*weight);
num-=k;
k*=2;
}
bag_01(num*cost,num*weight);
}//多重背包
AC代码:
#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iomanip>
#include<algorithm>
using namespace std;
int dp[100005],w[1005],c[1005];
int n,m;
int bag_01(int cost,int weight)//所占空间,价值
{
for(int i=m;i>=cost;i--)
dp[i]=max(dp[i],dp[i-cost]+weight);
}//01背包
int bag_cpt(int cost,int weight)//所占空间,价值
{
for(int i=cost;i<=m;i++)
dp[i]=max(dp[i],dp[i-cost]+weight);
}//完全背包
int bag_mul(int cost,int weight,int num)//所占空间,价值,数量
{
if(cost*num>=m)
{
bag_cpt(cost,weight);
return 1;
}
int k=1;
while(k<=num)
{
bag_01(k*cost,k*weight);
num-=k;
k*=2;
}
bag_01(num*cost,num*weight);
}//多重背包
int main()
{
while(1)
{
cin>>n>>m;
if(n==0&&m==0)
break;
for(int i=1;i<=n;i++)
{
cin>>c[i];//价值
}
for(int i=1;i<=n;i++)
{
cin>>w[i];//数目
}
for(int i=1;i<=m;i++)
{
dp[i]=-0xfffffff;
}
dp[0]=0;
for(int i=1;i<=n;i++)
{
bag_mul(c[i],c[i],w[i]);
}
int sum=0;
for(int i=1;i<=m;i++)
{
if(dp[i]>0)
sum++;
}
cout<<sum<<endl;
}
return 0;
}