HDU 2844 Coins——多重背包

来源:互联网 发布:mac锁定触控板快捷键 编辑:程序博客网 时间:2024/06/07 00:33

套用多重背包模板,如果发现这个代码在POJ 1742上超时,请看http://blog.csdn.net/hao_zong_yin/article/details/72585105

#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>using namespace std;const int maxn = 100000 + 10;int N, V, amount[maxn], capacity[maxn], weight[maxn];int dp[maxn];void bag01(int cost, int weight) {    for (int i = V; i >= cost; i--) {        dp[i] = max(dp[i], dp[i - cost] + weight);    }}void completebag(int cost, int weight) {    for (int i = cost; i <= V; i++) {        dp[i] = max(dp[i], dp[i - cost] + weight);    }}void multiplybag(int cost, int weight, int amount) {    if (cost * amount >= V) completebag(cost, weight);    else {        int k = 1;        while (k < amount) {            bag01(k * cost, k * weight);            amount -= k;            k += k;        }        bag01(amount * cost, amount * weight);    }}int main(){    while (scanf("%d %d", &N, &V) == 2 && N + V) {        memset(dp, 0, sizeof(dp));        for (int i = 1; i <= N; i++) scanf("%d", &capacity[i]);        for (int i = 1; i <= N; i++) scanf("%d", &amount[i]);        for (int i = 1; i <= N; i++) {            multiplybag(capacity[i], capacity[i], amount[i]);        }        int ans = 0;        for (int i = 1; i <= V; i++) {            if (dp[i] == i) ans++;        }        printf("%d\n", ans);    }}