Codeforces 2016 ACM Amman Collegiate Programming Contest A. Coins(动态规划/01背包变形)

传送门

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 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.

Sample Input

24 3 5 182 3 4 110 5 52 1 20 2010 3050

Sample Output

20

思路

题意:

给出两个集合,问有多少种组合形式使得一个集合的子集的和 S1 与另一个集合的子集的和 S2 满足条件 S1 + S2 = W 且 |S1 - S2| < K。

题解:

动态规划01背包的变形。dp[ i ]表示和为 i 共有多少种子集,那么动态规划方程即为 dp[ i ] = dp[ i ] + dp[ i - a[ x ] ]

//dp[ i ]表示和为 i 共有多少种子集
#include<bits/stdc++.h>
using namespace std;
typedef __int64 LL;
const int maxn = 100005;
const int mod = 1e9+7;
int dp[2][15500];
int main()
{
	int T;
	scanf("%d",&T);
	while (T--)
	{
		int n,m,k,w;
		scanf("%d%d%d%d",&n,&m,&k,&w);
		memset(dp,0,sizeof(dp));
		dp[0][0] = dp[1][0] = 1;
		for (int i = 1;i <= n;i++)
		{
			int x;
			scanf("%d",&x);
			for (int j = w;j >= x;j--)
			{
				dp[0][j] += dp[0][j-x];
				while (dp[0][j] >= mod)	dp[0][j] -= mod;
			}
		}
		for (int i = 1;i <= m;i++)
		{
			int x;
			scanf("%d",&x);
			for (int j = w;j >= x;j--)
			{
				dp[1][j] += dp[1][j-x];
				while (dp[1][j] >= mod)	dp[1][j] -= mod;
			}
		}
		LL ans = 0;
		for (int i = 0;i <= w;i++)
		{
			if (abs(w-i-i) <= k)	ans = (ans + (LL)dp[0][w-i]*dp[1][i])%mod;
		}
		printf("%I64d\n",ans);
	}
	return 0;
}

  

上一篇:(3.2)mysql基础深入——mysql源码阅读工具安装与应用


下一篇:nyoj 203 三国志(最短路加01背包)