EOJ 3009 Coins (II) 背包问题/多阶段动态规划

题目描述

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 ways you can make K using the coins.

For example, suppose there are three coins 1,2,5 and we can use coin 1 at most 3 times, coin 2 at most 2times and coin 5 at most 1 time. Then if K=5 the possible ways are:

  • 1112
  • 122
  • 5

So, 5 can be made in 3 ways.

输入格式

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 K (1≤K≤10 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 number of ways K can be made. Result can be large, so, print the result modulo 100 000 007.

样例

input

2
3 5
1 2 5 3 2 1
4 20
1 2 3 4 8 4 2 1

output

Case 1: 3
Case 2: 9

思路:和普通背包问题不一样,这题限制了每种物品(币种)的个数。一开始错误的思路是将所有硬币作为独一无二的物品,结果是会出现重复的组合。最终按照硬币种类来考虑,即在当前阶段是否引入新币种,若引入,则引入多少枚?设计状态dp[i][j]表示考虑前i个币种,能够凑出价格j的方案数。设当前币种i的面值为coin[i],最多可以使用number[i]个,则状态转移方程为dp[i][j]=dp[i-1][j]+dp[i-1][j-1*coin[i]]+dp[i-1][j-2*coin[i]]+...+dp[i-1][j-number[i]*coin[i]],即前i-1个币种的组合的基础上加上当前币种只取1个、2个到全部,或者不取的结果之和,代码中可用循环来完成。注意,dp[i][0]默认为1。

实现如下:

#include <iostream>
#include <cstring>
#define MAX 100000007

using namespace std;

int main()
{
    int cas, t=1;
    cin>>cas;
    while(t<=cas){
        int n, K;
        int coin[102], number[102];
        long long **dp = (long long**)malloc(102*sizeof(long long*));
        for(int i=0; i<102; ++i){
            dp[i] = (long long*)malloc(10001*sizeof(long long));
            memset(dp[i], 0, 10001*sizeof(long long));
        }
        dp[0][0] = 1;
        cin>>n>>K;
        for(int i=0; i<n; ++i)
            cin>>coin[i];
        for(int i=0; i<n; ++i)
            cin>>number[i];
        for(int i=0; i<n; ++i){
            for(int j=0; j<=K; ++j){
                for(int k=0; k<=number[i]; ++k){
                    if(j>=k*coin[i])
                        dp[i+1][j] = (dp[i+1][j] + dp[i][j-k*coin[i]]) % MAX;
                }
            }
        }
        cout<<"Case "<<t++<<": "<<dp[n][K]<<endl;
    }
    return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值