Coin Change (II)

In a strange shop there are n types of coins of value A1, A2 ... An. You have to find the number of ways you can make K using the coins. You can use any coin at most K times.

For example, suppose there are three coins 1, 2, 5. Then if K = 5 the possible ways are:

11111

1112

122

5

So, 5 can be made in 4 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 ≤ 100) and K (1 ≤ K ≤ 10000). The next line contains n integers, denoting A1, A2 ... An (1 ≤ Ai ≤ 500). 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

4 20

1 2 3 4

Sample Output

Case 1: 4

Case 2: 108

題意:你有n種不同面值的硬幣,要用這些硬幣來組合成K,每種硬幣不得使用超過k次(怎麼可能超過k次)

解析:先來看第一種方法:

  假設我們用a[i]來表示第i種硬幣的面額,用dp[i][j]來表示,在選用前i種硬幣的情況下,有多少種組成j的方案。

  那麼可以有遞推式:dp[i][j]=dp[i-1][j-a[i]]+dp[i-1][j-2*a[i]].......dp[i-1][j-k*a[i]];

  那麼我們可以嘗試着去簡化一下這個式子,雖然爲了做出這道題,沒有必要去簡化,但是爲了把我的代碼貼出來,還是需要簡化一下的。假如我們使用dp[i]來表示用當前的硬幣來組成i有多少種方案,那麼我們知道,dp[i]=dp[i-a[j]](j=1~n)但是,這樣寫遞推式,會導致112和121被視爲兩種情況,那麼我們應該如何解決這樣的問題呢,答案是,我們需要將硬幣一個個地引入,然後每引入一個新的硬幣,就去刷新一遍dp數組,下面的話看一下代碼應該就可以理解了。

  

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
int n,k;
int a[10000];
int dp[200000];
int main(){
	int T;
	cin>>T;
	int cnt=0;
	while(T--){
		memset(a,0,sizeof(a));
		memset(dp,0,sizeof(dp));
		cin>>n>>k;
		for(int i=1;i<=n;i++){
			scanf("%d",&a[i]);
		}
		dp[0]=1;
		sort(a+1,a+1+n);
		for(int cass=1;cass<=n;cass++){
			int curr=a[cass];
			if(a[cass]!=a[cass-1]){
				for(int i=curr;i<=k;i++){
					if(curr<=i){
						dp[i]+=dp[i-curr];
						dp[i]%=100000007;
					}
				}
			}
		}
		printf("Case %d: %d\n",++cnt,dp[k]);
	}
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章