zoukankan      html  css  js  c++  java
  • 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

    思路

    意思就是给你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;
    }
    
  • 相关阅读:
    安卓学习第25课——imageswitcher
    安卓学习第24课——viewSwitcher
    安卓学习第23课——ratingBar
    安卓学习第22课——seekBar
    减治求有重复元素的全排列
    【POJ 1182 食物链】并查集
    【POJ 2823 Sliding Window】 单调队列
    ID3算法 决策树 C++实现
    用BFS和DFS解决圆盘状态搜索问题
    用哈希表实现图书管理系统
  • 原文地址:https://www.cnblogs.com/hhlya/p/13099851.html
Copyright © 2011-2022 走看看