Cod sursa(job #20331)
//100p
#include <stdio.h>
#include <string.h>
#include <algorithm>
#define MAX(a, b) ( (a) < (b) ? (b) : (a) )
#define MMAX 300001
#define NMAX 21
#define PMAX 20
#define KMAX 5
using namespace std;
int A[NMAX][NMAX][KMAX + 1];
int S[NMAX][NMAX][KMAX + 1];
int V[MMAX], St[NMAX], U[NMAX];
int i, j, k, N, M;
int K, P, maxs, sum, rest, sm;
void back(int i, int r)
{
int k, j;
if (i > K - 1)
{
sum = 0;
memset(U, 0, sizeof(U));
rest = (4 * P - sm) % P, St[K] = rest;
for (j = 1; j <= K; j++) U[St[j]]++;
for (j = 0; j < P; j++)
if (U[j] > A[P][j][0]) { sum = -1; break; }
else sum += S[P][j][U[j]];
maxs = MAX(maxs, sum);
}
else
{
for (k = r; k < P; k++)
{
sm += k, St[i] = k;
back(i + 1, k);
sm -= k, St[i] = -1;
}
}
}
int main()
{
freopen("tricouri.in", "r", stdin);
freopen("tricouri.out", "w", stdout);
scanf("%d %d", &N, &M);
for (i = 1; i <= N; i++) scanf("%d", &V[i]);
sort(V + 1, V + N + 1);
for (i = N; i >= 1; i--)
{
for (j = 2; j <= PMAX; j++)
if (A[j][V[i] % j][0] < KMAX)
{
k = V[i] % j;
int nr = ++A[j][k][0];
A[j][k][nr] = V[i], S[j][k][nr] = S[j][k][nr - 1] + A[j][k][nr];
}
}
for (i = 1; i <= M; i++)
{
maxs = -1, sum = 0, rest = 0, sm = 0;
for (j = 0; j <= KMAX; j++) St[j] = -1;
scanf("%d %d", &K, &P);
back(1, 0);
printf("%d\n", maxs);
}
return 0;
}