EOJ 3010 Coins (III) 多重背包的可行性问题

问题描述

In a strange shop there are n types of coins of value A1,A2,…,An. C1,C2,…,Cn denote the number of coins of value A1,A2,…,An respectively. You have to find the number of different values (from 1 to m), which can be produced using these coins.

输入格式

Input starts with an integer T (T≤10), denoting the number of test cases.

Each case starts with a line containing two integers n (1≤n≤100) and m (1≤K≤100 000). The next line contains 2n integers, denoting A1,A2,…,An,C1,C2,…,Cn (1≤Ai≤100 000,1≤Ci≤1 000). All Ai will be distinct.

输出格式

For each case, print the case number and the result.

样例

input

2
3 10
1 2 4 2 1 1
2 5
1 4 2 1

output

Case 1: 8
Case 2: 4

思路:一开始用基本的部分背包解法会超时 ,看了解答发现还是需要技巧的。。。状态方程dp[j+A[i]] = max(dp[j+A[i]], dp[j]-1),其中dp[j]在每一轮循环中表示当前币种i在凑到金额j时还可以使用的数量,初始值为C[i],即最大可用量。每次更新时保证剩余可用的硬币数最多,这样可以尽量多的凑出不同的金额,代码如下:

#include <iostream>
#include <cstring>

using namespace std;

int main()
{
    int T;
    cin>>T;
    for(int cas=1; cas<=T; ++cas){
        int n, m, cnt=0;
        int A[101], C[101];
        int *dp = (int*)malloc(100001*sizeof(int));
        memset(dp, -1, 100001*sizeof(int));
        dp[0] = 0;
        cin>>n>>m;
        for(int i=0; i<n; ++i)
            cin>>A[i];
        for(int i=0; i<n; ++i)
            cin>>C[i];
        for(int i=0; i<n; ++i){//考虑每个币种
            for(int j=0; j<=m; ++j)//初始化
                if(dp[j]>=0)//若当前金额可以由前i-1种硬币凑到
                    dp[j] = C[i];//则在该金额的基础上还可以叠加C[i]个币种i
            for(int j=0; j+A[i]<=m; ++j)//再次循环,开始分配币种个数
                if(dp[j]>0)//如果当前金额还可以叠加的币种i个数大于0,则考虑是叠加还是不叠加
                    dp[j+A[i]] = max(dp[j+A[i]], dp[j]-1);//选择叠加后剩余可用硬币数量多的情况,因为这样可以凑出更多种金额
        }
        for(int i=1; i<=m; ++i)
            if(dp[i]>=0)//统计可得金额
                ++cnt;
        printf("Case %d: %d\n", cas, cnt);
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值