hdu 2844 coins 多重背包

来源:互联网 发布:web编程语言有哪些 编辑:程序博客网 时间:2024/06/14 12:50

Coins

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 17033    Accepted Submission(s): 6737


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 101 2 4 2 1 12 51 4 2 10 0
 

Sample Output
84
题意: 给你n种硬币 和 硬币的数量 给你一个 m 的大小限制
你的任务是 得出有用现有的硬币能组成多少种 小于等于m的数
思路: 其实我感觉最重要的是 m 这个限制 ,就是相当给你一个大小为m的背包
问你是否能够正好装满这个背包 这样的话 我们就可以枚举m 的大小 计算出m大的背包 是否能够正好装满。。 如果可以正好装满 那么就是可以根据当前的硬币组成这个 小于等于m 的数 那么就 ans++
当一个硬币的cnt*val>=m 的时候 相当于 !!! 可以无限取 所以就用完全背包 不然用 二进制优化的01背包 。
代码:
#include<stdio.h>#include<string.h>#include<iostream>#include<algorithm>#define N 105#define M 100005using namespace std;int cnt[N];int val[N];int dp[M];int n,m;int main(){while(cin>>n>>m){if(n==0&&m==0) break;for(int i=1;i<=n;i++){cin>>val[i];}for(int i=1;i<=n;i++) cin>>cnt[i];memset(dp,0,sizeof(dp));for(int i=1;i<=n;i++){if(cnt[i]*val[i]>=m){for(int j=val[i];j<=m;j++){dp[j]=max(dp[j],dp[j-val[i]]+val[i]);}}else{int c=cnt[i];int k=1;while(k<c){for(int j=m;j>=k*val[i];j--){dp[j]=max(dp[j],dp[j-k*val[i]]+k*val[i]);}c-=k;k*=2;}for(int j=m;j>=c*val[i];j--){dp[j]=max(dp[j],dp[j-c*val[i]]+c*val[i]);    }}}int ans=0;for(int i=1;i<=m;i++) if(dp[i]==i) ans++;printf("%d\n",ans);}return 0;} 



原创粉丝点击