Given a list of N numbers you will be allowed to choose any M of them. So you can choose in NCM 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 Nnumbers. 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 Output for 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 | SET 1: QUERY 1: 2 QUERY 2: 9 SET 2: QUERY 1: 1 |
题意:求在n个数中选m个数的和为d的倍数的方案数
感觉是搜索,但觉着这个题目不是很合适,用dp来做,dp[i][j][k]表示在前i个数中选j个的和%d为k的数量
背包解法:http://blog.csdn.net/junior19/article/details/54719076
代码:
#include<iostream>
#include<string>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<queue>
#include<cstring>
#include<map>
using namespace std;
typedef long long ll;
#define M 205
int n,q,m,mod;
int a[205];
ll dp[205][30][30];
ll work()
{
int i,j,k;
memset(dp,0,sizeof(dp));
dp[0][0][0]=1;
for(i=1;i<=n;i++)
{
dp[i][0][0]=1;
for(j=1;j<=m;j++)
for(k=0;k<mod;k++)
{
dp[i][j][k]+=dp[i-1][j][k];
dp[i][j][k]+=dp[i-1][j-1][(k-a[i]%mod+mod)%mod];
}
}
return dp[n][m][0];
}
int main()
{
int i,cas=0;
while(scanf("%d%d",&n,&q)!=EOF)
{
if(n==0&&q==0) break;
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("SET %d:\n",++cas);
for(i=1;i<=q;i++)
{
scanf("%d%d",&mod,&m);
printf("QUERY %d: %lld\n",i,work());
}
}
return 0;
}
看到另一个写法也比较好理解:
#include<iostream>
#include<string>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<queue>
#include<cstring>
#include<map>
using namespace std;
typedef long long ll;
#define M 205
int n,q,m,mod;
int a[205];
ll dp[205][30][30];
ll work()
{
int i,j,k;
memset(dp,0,sizeof(dp));
dp[0][0][0]=1;
for(i=0;i<n;i++)
for(j=0;j<=m;j++)
for(k=0;k<mod;k++)
{
dp[i+1][j][k]+=dp[i][j][k];
dp[i+1][j+1][((a[i+1]%mod)+mod+k)%mod]+=dp[i][j][k];
}
return dp[n][m][0];
}
int main()
{
int i,cas=0;
while(scanf("%d%d",&n,&q)!=EOF)
{
if(n==0&&q==0) break;
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("SET %d:\n",++cas);
for(i=1;i<=q;i++)
{
scanf("%d%d",&mod,&m);
printf("QUERY %d: %lld\n",i,work());
}
}
return 0;
}