LightOJ

先上题目:

1231 - Coin Change (I)
Time Limit: 1 second(s) Memory Limit: 32 MB

In a strange shop there are n types of coins of value A1, A2 ... AnC1, 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

Output for Sample Input

2

3 5

1 2 5 3 2 1

4 20

1 2 3 4 8 4 2 1

Case 1: 3

Case 2: 9

  题意:有n种硬币,每种硬币有一定的数量以及价值,给你一个数k,问你有多少种方法可以用这些硬币凑出k。

  背包问题,是一个多重背包,因为同一种硬币的数量上限比较少,所以可以直接枚举同一种硬币不同数量的情况。

  dp[i][j]的含义:前i种银币可以凑出j的方法有多少种?

  对于第i种硬币,初始化的时候是dp[i][l*a[i]]=1 意思是对于第i种硬币,如果同时选l个硬币的时候l*a[i]<=k那么就有一种方法。

  那么状态转移方程就是dp[i][j]=(dp[i][j]%MOD+dp[i-1][j-l*a[i]]%MOD)%MOD 意思就是对于前i种硬币的方法来自两部分,①第i种硬币自己本身凑出来了,②用l个第i种硬币加上前面凑出j-l*a[i]这么多钱的方法数量。

  这种背包和之前做的那些问题相比,最优子结构需要更多的分析才能发现。看来DP还要努力啊。

上代码:

 1 #include <cstdio>
 2 #include <cstring>
 3 #define MAX 52
 4 #define MAXN 1002
 5 #define MOD 100000007
 6 using namespace std;
 7 
 8 int a[MAX];
 9 int c[MAX];
10 int dp[MAX][MAXN];
11 
12 int main()
13 {
14     int t,n,k;
15     //freopen("data.txt","r",stdin);
16     scanf("%d",&t);
17     for(int u=1;u<=t;u++){
18         scanf("%d %d",&n,&k);
19         memset(dp,0,sizeof(dp));
20         for(int i=1;i<=n;i++){
21             scanf("%d",&a[i]);
22         }
23         for(int i=1;i<=n;i++){
24             scanf("%d",&c[i]);
25         }
26         for(int i=1;i<=n;i++){
27             for(int j=1;j<=c[i];j++){
28                 if(j*a[i]<=k){
29                     dp[i][j*a[i]]=1;
30                 }
31             }
32         }
33         for(int i=1;i<=n;i++){
34             for(int j=1;j<=k;j++){
35                 for(int l=0;l<=c[i];l++){
36                     if(l*a[i]<j){
37                         dp[i][j]=(dp[i][j]%MOD+dp[i-1][j-l*a[i]]%MOD)%MOD;
38                     }
39                 }
40             }
41         }
42         printf("Case %d: %d
",u,dp[n][k]%MOD);
43     }
44     return 0;
45 }
1231
原文地址:https://www.cnblogs.com/sineatos/p/3581360.html