Coin Change (I)
Description
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 2 times 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
Input starts with an integer T (≤ 100), denoting the number of test cases.
Each case starts with a line containing two integers n (1 ≤ n ≤ 50) and K (1 ≤ K ≤ 1000). The next line contains 2n integers, denoting A1, A2 ... An, C1, C2 ... Cn (1 ≤ Ai ≤ 100, 1 ≤ Ci ≤ 20). All Ai will be distinct.
Output
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 100000007.
Sample Input
2
3 5
1 2 5 3 2 1
4 20
1 2 3 4 8 4 2 1
Sample Output
Case 1: 3
Case 2: 9
解题思路:
给你n个物品的体积和数量,让你求有多少种组合能恰好装满m体积的背包。
用dp[i][j]表示前i种物品,组成j的容量有几种组法,则状态转移方程为:
dp[i][j] += dp[i-1][j-k*a[i]];
枚举第i种物品的时候可以取一个,取两个,。。,当然最后别忘了:也可以不取。
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int MOD = 100000007;
const int maxn = 1005;
int dp[55][maxn];
int a[55],b[55];
int main(){
int T,t = 1;
scanf("%d",&T);
while(T--){
int n,m;
scanf("%d%d",&n,&m);
for(int i = 1; i <= n; i++)
scanf("%d",&a[i]);
for(int i = 1; i <= n; i++)
scanf("%d",&b[i]);
memset(dp,0,sizeof(dp));
dp[0][0] = 1;
for(int i = 1; i <= n; i++){
for(int j = m; j >= 0; j--){
for(int k = 1; k <= b[i]; k++) {
if(j-k*a[i] >= 0)
dp[i][j] += dp[i-1][j-k*a[i]];
}
}
for(int j = 0; j <= m; j++)
dp[i][j] = (dp[i][j]+dp[i-1][j])%MOD;
}
printf("Case %d: %d\n",t++,dp[n][m]);
}
return 0;
}
本文介绍了一个经典的背包问题——CoinChange,并提供了一种有效的动态规划解决方案。问题旨在利用不同面额的硬币组合来构成给定的目标金额,探讨了如何计算可能的组合数。文章还分享了AC代码实现,帮助读者理解算法的具体应用。
645

被折叠的 条评论
为什么被折叠?



