uva 10616 - Divisible Group Sums(计数)

题目链接:uva 10616 - Divisible Group Sums


题目大意:给出n和q,表示有n个数字,q次询问,然后给出n个数字,q次询问,每次询问有两个数值,D和N,计算出n个数字中选出N个数字的和能整除D的方案有多少种。


解题思路:因为(a + b)% D = (a%D+b%D)%D,所以可以将所有的数字全先模掉D,这样计算量会比较少,然后利用dp中背包的思想,计算出用i个数组成数值为j的可能dp[i][j]。


#include <stdio.h>
#include <string.h>
const int N = 205;

int n, q, num[N], rec[N];
long long dp[15][N * N];

void read() {	
	for (int i = 0; i < n; i++)
		scanf("%d", &num[i]);
}

void solve(int cas) {
	int D, N, sum = 0;
	long long ans = 0;
	scanf("%d%d", &D, &N);
	for (int i = 0; i < n; i++) {
		rec[i] = (num[i] % D + D) % D;
		sum += rec[i];
	}

	memset(dp, 0, sizeof(dp));
	dp[0][0] = 1;
	for (int i = 0; i < n; i++) {
		for (int j = N - 1; j >= 0; j--) {
			for (int k = 0; k <= sum; k++)
				dp[j + 1][k + rec[i]] += dp[j][k];
		}
	}
			

	for (int i = 0; i <= sum; i += D)
		ans += dp[N][i];
	printf("QUERY %d: %lld\n", cas, ans);
}

int main () {
	int cas = 1;
	while (scanf("%d%d", &n, &q), n + q) {
		read();
		printf("SET %d:\n", cas++);
		for (int i = 0; i < q; i++)
			solve(i + 1);
	}
	return 0;
}


你可能感兴趣的:(uva 10616 - Divisible Group Sums(计数))