lightoj1231--Coin Change (I)(简单dp,背包计数)

来源:互联网 发布:3d出号绝密算法 编辑:程序博客网 时间:2024/05/19 18:39

Description

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 ifK = 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体积的背包

思路很简单,就是枚举第i个物体放入Ci个的情况下,用前i-1个物体去填补M-Ci*Ai体积的值累和

但写法有两种,递归与非递归。思路上没有区别,但非递归在复杂度系数上较小

先给出两种代码:


递归:

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <queue>#include <cmath>#include <stack>#include <map>using namespace std;typedef long long ll;int d[55][1005];int a[55];int b[55];int dp(int n,int m){    if(d[n][m]>=0)  return d[n][m];    if(n==0)    {        if(m%a[0]==0&&m/a[0]<=b[0])return  d[n][m]=1;        else return d[n][m]=0;    }    int res=0;    for(int i=0;i<=b[n]&&i*a[n]<=m;i++)        res+=dp(n-1,m-i*a[n]);    return d[n][m]=res%100000007;}int main(){    int t,fir=1;    cin>>t;    while(t--)    {        int n,m;        scanf("%d %d",&n,&m);        for(int i=0;i<n;i++)            scanf("%d",&a[i]);        for(int i=0;i<n;i++)            scanf("%d",&b[i]);        printf("Case %d: ",fir++);        memset(d,-1,sizeof(d));        cout<<dp(n-1,m)<<endl;    }    return 0;}

非递归:

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <queue>#include <cmath>#include <stack>#include <map>using namespace std;typedef long long ll;int a[55];int b[55];int dp[55][1005];int main(){    int t,fir=1;    cin>>t;    while(t--)    {        int n,k;        cin>>n>>k;        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=0; j<=b[i]; j++)                for(int h=k; h>=j*a[i]; h--)                {                    dp[i][h]+=dp[i-1][h-j*a[i]];                    dp[i][h]%=100000007;                }                  printf("Case %d: ",fir++);        cout<<dp[n][k]<<endl;    }    return 0;}

运行时间比较:


0 0
原创粉丝点击