Codeforces gym 101102 A dp

来源:互联网 发布:广州淘宝拍照的地方 编辑:程序博客网 时间:2024/05/19 22:51

Coins
time limit per test
3 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Hasan and Bahosain want to buy a new video game, they want to share the expenses. Hasan has a set of N coins and Bahosain has a set of M coins. The video game costs W JDs. Find the number of ways in which they can pay exactly W JDs such that the difference between what each of them payed doesn’t exceed K.

In other words, find the number of ways in which Hasan can choose a subset of sum S1 and Bahosain can choose a subset of sum S2such that S1 + S2 = W and |S1 - S2| ≤ K.

Input

The first line of input contains a single integer T, the number of test cases.

The first line of each test case contains four integers NMK and W (1 ≤ N, M ≤ 150) (0 ≤ K ≤ W) (1 ≤ W ≤ 15000), the number of coins Hasan has, the number of coins Bahosain has, the maximum difference between what each of them will pay, and the cost of the video game, respectively.

The second line contains N space-separated integers, each integer represents the value of one of Hasan’s coins.

The third line contains M space-separated integers, representing the values of Bahosain’s coins.

The values of the coins are between 1 and 100 (inclusive).

Output

For each test case, print the number of ways modulo 109 + 7 on a single line.

Example
input
24 3 5 182 3 4 110 5 52 1 20 2010 3050
output
20


题意:第一个人有n枚硬币  第二个人有m枚硬币  两个人付的钱数差不能超过k  组成w的方案数


题解:先用dp求出两个人小于w钱数的方案  然后枚举k  求出答案  累加


#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>using namespace std;typedef long long ll;const ll MOD = (ll)1e9+7;ll dp1[15005],dp2[15005];int main(){int t;scanf("%d",&t);while(t--){memset(dp1,0,sizeof(dp1));memset(dp2,0,sizeof(dp2));int n,m,w,k;scanf("%d%d%d%d",&n,&m,&k,&w);int sum=0;dp1[0]=dp2[0]=1;for(int i=1;i<=n;i++){int x;scanf("%d",&x);sum+=x;for(int j=sum;j>=x;j--){dp1[j]+=dp1[j-x];dp1[j]%=MOD;}}sum=0;for(int i=1;i<=m;i++){int x;scanf("%d",&x);sum+=x;for(int j=sum;j>=x;j--){dp2[j]+=dp2[j-x];dp2[j]%=MOD;}}ll ans=0;for(int i=0;i<=w;i++){int j=w-i;if(abs(i-j)>k)continue;ans+=dp1[i]*dp2[j]%MOD;ans%=MOD;}printf("%lld\n",ans);}return 0;}


0 0
原创粉丝点击