Description
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 ofM 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 S2 such 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 N, M, K 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.
Sample Input
2
4 3 5 18
2 3 4 1
10 5 5
2 1 20 20
10 30
50
2
0
题目链接:http://codeforces.com/gym/101102/problem/A
题意:有两个序列分别有n和m个元素,现在要从两个序列中分别选出两个子集,设他们的和分别是S1和S2,现在使得选出来的结果满足以下两个条件
|S1-S2|<=K,S1+S2 = W;求有多少种选法,结果对1e9+7求余;
对于序列1,可以用dp[i][j]来表示前i个元素的子集构成和为 j 的方法数;那么就可以看成01背包来做即可;
dp[0] = 1;
dp[j] = (dp[j]+dp[j-a[i]])%mod;
两个序列处理完之后得到dp1和dp2,然后对应求结果即可;
#include <stdio.h> #include <algorithm> #include <cstring> #include <cmath> using namespace std; typedef long long LL; const int N = 15010; const double eps = 1e-10; const int INF = 0x3f3f3f3f; const int mod = 1e9+7; int n, m, k, w; int a[155], b[155]; LL dp1[N], dp2[N]; int main() { int T; scanf("%d", &T); while(T--) { memset(dp1, 0, sizeof(dp1)); memset(dp2, 0, sizeof(dp2)); scanf("%d %d %d %d", &n, &m, &k, &w); for(int i=1; i<=n; i++) scanf("%d", &a[i]); for(int i=1; i<=m; i++) scanf("%d", &b[i]); dp1[0] = dp2[0] = 1; for(int i=1; i<=n; i++) { for(int j=15000; j>=a[i]; j--) dp1[j] = (dp1[j]+dp1[j-a[i]])%mod; } for(int i=1; i<=m; i++) { for(int j=15000; j>=b[i]; j--) dp2[j] = (dp2[j] + dp2[j-b[i]])%mod; } LL ans = 0; for(int i=0; i<=w; i++) { int j=w-i; if(max(i, j) - min(i, j) > k) continue; ans = (ans + dp1[i]*dp2[j]%mod) % mod; } printf("%I64d ", ans); } return 0; }