UVA10616 Divisible Group Sums组合+0-1背包
Posted 海岛Blog
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UVA10616 Divisible Group Sums组合+0-1背包相关的知识,希望对你有一定的参考价值。
Given a list of N numbers you will be allowed to choose any M of them. So you can choose in
(
N
M
)
\\tbinom{N}{M}
(MN)ways. You will have to determine how many of these chosen groups have a sum, which is divisible by D.
Input
The input file contains maximum ten sets of inputs. The description of each set is given below.
The first line of each set contains two integers N (0 < N ≤ 200) and Q (0 < Q ≤ 10). Here N indicates how many numbers are there and Q is the total no of query. Each of the next N lines contains one 32 bit signed integer. Our queries will have to be answered based on these N numbers. Next Q lines contain Q queries. Each query contains two integers D (0 < D ≤ 20) and M (0 < M ≤ 10) whose meanings are explained in the first paragraph.
Input is terminated by a case whose N = 0 and Q = 0. This case should not be processed.
Output
For each set of input, print the set number. Then for each query in the set print the query number followed by the number of desired groups. See sample output to know the exact output format.
Sample Input
10 2
1
2
3
4
5
6
7
8
9
10
5 1
5 2
5 1
2
3
4
5
6
6 2
0 0
Sample Output
SET 1:
QUERY 1: 2
QUERY 2: 9
SET 2:
QUERY 1: 1
问题链接:UVA10616 Divisible Group Sums
问题简述:给定n个数,从中取出m个,使得它们之和能整除d,问有多少种取法?
问题分析:组合问题,用0-1背包来解决,不解释。
程序说明:(略)
参考链接:(略)
题记:(略)
AC的C++语言程序如下:
/* UVA10616 Divisible Group Sums */
#include <bits/stdc++.h>
using namespace std;
const int N = 200;
const int M = 10;
int a[N], t[N], dp[M + 1][N * N];
int main()
{
int n, q, d, m, caseno = 0;
while (~scanf("%d%d", &n, &q) && (n || q)) {
int sum = 0;
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
printf("SET %d:\\n", ++caseno);
for (int qs = 1; qs <= q; qs++) {
scanf("%d%d", &d, &m);
for (int i = 0; i < n; i++) {
t[i] = (a[i] % d + d) % d;
sum += t[i];
}
memset(dp, 0, sizeof dp);
dp[0][0] = 1;
for (int i = 0; i < n; i++)
for (int j = m - 1; j >= 0; j--)
for (int k = 0; k <= sum; k++)
dp[j + 1][k + t[i]] += dp[j][k];
long long ans = 0;
for (int i = 0; i <= sum; i += d)
ans += dp[m][i];
printf("QUERY %d: %lld\\n", qs, ans);
}
}
return 0;
}
以上是关于UVA10616 Divisible Group Sums组合+0-1背包的主要内容,如果未能解决你的问题,请参考以下文章
Light oj 1125 - Divisible Group Sums (dp)
LeetcodeLargest Divisible Subset