首页 > 编程知识 正文

HDUOJ 2844 Coins

时间:2023-05-06 09:34:37 阅读:230613 作者:1563

HDUOJ 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 xsdqd’s coins of value A1,A2,A3…An then calculate how many prices(form 1 to m) xsdqd 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

典型的多重背包,但是题目卡了时间,也即如果将多重背包直接转为 01 背包会超时,所以此时要考虑背包的二进制优化,一般的 01 背包我们对物品的数量 n n n,必须要开出一样大的数组,但是通过二进制转化, n = 2 a 1 + 2 a 2 + ⋯ + 2 a k n=2^{a_1}+2^{a_2}+cdots+2^{a_k} n=2a1​+2a2​+⋯+2ak​,就可以将 n n n 的存储空间离散成 k k k 个,从而大大减少空间和时间的开销,打个比方:

27=2^4+2^3+2^1+2^0 -> 27位的空间只需5位空间即可存储

通过优化我们只需将权值分散到每一个二进制位即可,AC代码如下:

#include<bits/stdc++.h>using namespace std;typedef long long ll;int num[110],c[110],v[10005],dp[100005];int main(){ int n,m; while(~scanf("%d%d",&n,&m)&&(n||m)){ int cnt=0,ans=0; for(int i=0;i<n;i++) scanf("%d",&c[i]); for(int i=0;i<n;i++){ scanf("%d",&num[i]); for(int j=1;num[i]>0;j*=2){ int x=min(num[i],j); v[cnt++]=x*c[i]; num[i]-=x; } } memset(dp,0,sizeof(dp)); dp[0]=1; for(int i=0;i<cnt;i++){ for(int j=m;j>=v[i];j--){ if(dp[j-v[i]]) dp[j]=1; } } for(int i=1;i<=m;i++) if(dp[i]) ans++; printf("%dn",ans); }}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。