Coins
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.
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.
For each test case output the answer on a single line.
3 10
1 2 4 2 1 1
2 5
1 4 2 1
0 0
8
4
给n种硬币的面值及其数量购买手表,手表的价格不超过m,问手表价格可以有多少种可以表示?
也就是用手中的硬币能表示多少价格。
输入n,m,然后输入2n个数,前n个数为硬币的面值,后n个数为
例:2 5
1 4 2 1
共有4种价格可以表示:
6(4+1+1),因为6>m=5
很明显是多重背包,初始化dp[i]=0,dp[0]=1。dp[i]=1表示该价格可以表示出来。
则dp[i]的表达式为
d p [ i ] = 1 ( d p [ j ] + w ≤ m ) dp[i]= 1 \space \space \space \space \space ({dp[j]+w \leq m}) dp[i]=1 (dp[j]+w≤m)
如果只二进制拆分,转换为01背包,交了几发全T了,QAQ
注意:单纯二进制拆分会T,必须转化为完全背包和01背包
#include
#include
#include
#include
#define MAXL 100010
#define INF 0x3f3f3f3f
using namespace std;
int dp[MAXL];
int fw[MAXL],fv[MAXL];
void init(){
memset(w,0,sizeof(w));
memset(v,0,sizeof(v));
memset(dp,0,sizeof(dp));
}
int main(){
int n,m;
while (scanf("%d%d",&n,&m)!=EOF){
if (!n && !m)break;
init();
for (int i=0;i<n;i++){
scanf("%d",&fw[i]);
}
for (int i=0;i<n;i++){
scanf("%d",&fv[i]);
}
dp[0]=1;
for (int i=0;i<n;i++){
if (fw[i]*fv[i]<=m){
//01背包
int ww=0;
for (int j=1;j<=fv[i];j<<=1){
fv[i]-=j;
ww=fw[i]*j;
for (int k=m;k>-1;k--){
if (dp[k] && k+ww<=m){
dp[k+ww]=1;
}
}
}
if (fv[i]!=0){
ww=fw[i]*fv[i];
for (int k=m;k>-1;k--){
if (dp[k] && k+ww<=m){
dp[k+ww]=1;
}
}
}
}else{
//完全背包
for (int k=0;k<=m;k++){
if (dp[k] && k+fw[i]<=m){
dp[k+fw[i]]=1;
}
}
}
}
int ans=0;
for (int i=1;i<=m;i++){
if (dp[i]>0){
ans++;
}
}
printf("%d\n",ans);
}
return 0;
}