hdu 2844 coins(多重背包 二进制拆分法)

Problem 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
 
题意:给面值不同,有固定个数的硬币,能有多少种不同的不同总面值的组合方式;
思路: 我用的是完全背包的二进制拆分法
#include <cstdio>
#include <map>
#include <iostream>
#include<cstring>
#include<bits/stdc++.h>
#define ll long long int
#define M 6
using namespace std;
inline ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
inline ll lcm(ll a,ll b){return a/gcd(a,b)*b;}
int moth[]={,,,,,,,,,,,,};
int dir[][]={, ,, ,-, ,,-};
int dirs[][]={, ,, ,-, ,,-, -,- ,-, ,,- ,,};
const int inf=0x3f3f3f3f;
const ll mod=1e9+;
int n,m;
int a[];
int c[];
int dp[];
int main(){
ios::sync_with_stdio(false);
while(cin>>n>>m){
if(!n&&!m) break;
memset(dp,,sizeof(dp));
for(int i=;i<=n;i++)
cin>>a[i];
for(int i=;i<=n;i++)
cin>>c[i];
dp[]=;
for(int i=;i<=n;i++){
int temp=c[i]; int now=;
while(){ //把c[i]拆解成若干个2的幂次方
if(temp>now){
temp-=now;
for(int j=m;j>=now*a[i];j--)
if(dp[j-now*a[i]])
dp[j]=;
now*=;
}else{
for(int j=m;j>=temp*a[i];j--)
if(dp[j-temp*a[i]])
dp[j]=;
break;
}
}
}
int ans=;
for(int i=;i<=m;i++)
if(dp[i])
ans++;
cout<<ans<<endl;
}
}
上一篇:clipboard让复制的文本换行


下一篇:LinkedHashMap源码分析