ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

HDU 2844 Coins (多重背包+二进制优化)

2020-06-12 15:56:29  阅读:209  来源: 互联网

标签:... HDU coins int 2844 Coins maxn include dp


题面

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

思路

意思就是给你n种硬币,并给出每种硬币的价值和个数,问可以组合成为多少个不超过m的正整数。当然问朴素的思路很容易想,直接多重背包枚举,由于这样会超时,所以我们采取二进制进行优化,然后在重新分成的堆里面进行01背包操作,枚举出不超过m的背包容量下的价值,当然这里的价值和容量都是钱的数目,最后枚举1-m,查看是否dp[i]==i就可以了。

代码实现

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<iostream>
using namespace std;
const int maxn = 10005;
int n,m;
int c[maxn], val[maxn], dp[maxn], a[maxn];
int binary () {
    int k=0;
    for (int i=1;i<=n;i++) {
        for (int j=1;j<=c[i];j<<=1) {
            a[k++]=j*val[i];
            c[i]-=j;
        }
        if (c[i]>0) {
            a[k++]=c[i]*val[i];
        }
    }
    return k;
}
int main () {
    while (cin>>n>>m) {
        int count=0;
        if (n==0&&m==0) break;
        for (int i=1;i<=n;i++) cin>>c[i];
        for (int i=1;i<=n;i++) cin>>val[i];
        int k=binary();
        for (int i=1;i<=k;i++) {
            for (int j=m;j>=a[i];j--) {
                dp[j]=max(dp[j],dp[j-a[i]]+a[i]);
            }
        }
        for (int i=1;i<=m;i++) {
            if (dp[i]==i) count++;
        }
        cout<<count<<endl;
    }
    return 0;
}

标签:...,HDU,coins,int,2844,Coins,maxn,include,dp
来源: https://www.cnblogs.com/hhlya/p/13099851.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有