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;
    }
    
  • 相关阅读:
    C-Lodop 非典型应用
    这里有个坑---js日期格式yyyy-MM-dd与yyyy/MM/dd
    这里有个坑---[NotMapped]不要忘了加
    这里有个坑---entity为null的问题
    数据库优化小技巧总结
    前端优化小技巧总结
    前端日志探讨二
    25.密码学知识-对称加密-2——2019年12月19日
    24.mongodb可视化工具部署——2019年12月19日
    22.Express框架——2019年12月19日
  • 原文地址:https://www.cnblogs.com/hhlya/p/13099851.html
Copyright © 2011-2022 走看看