题目描述:
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 1output
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;
}