Pagini recente » Cod sursa (job #2571691) | Cod sursa (job #503683) | Cod sursa (job #2451124) | Cod sursa (job #591767) | Cod sursa (job #785212)
Cod sursa(job #785212)
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
ifstream f("tricouri.in");
ofstream g("tricouri.out");
#define Kmax 6
#define Pmax 21
#define nmax 300005
int n, m, a[nmax], dp[Kmax][Pmax], acum[Kmax][Pmax];
bool cmp(int a, int b){
return a > b;
}
void citeste(){
f >> n >> m;
for(int i=1; i<=n; ++i) f >> a[i];
sort(a+1, a+n+1, cmp);
}
void rezolva(){
//dp[k][p] = suma obtinuta avand k elemente care dau restul p
for(int i=1; i<=m; i++){
int K, P;
f >> K >> P;
int ok = 0;
for(int w=0; w<Kmax; w++) for(int j=0; j<Pmax; j++) dp[w][j] = 0;
for(int i=1; i<=n; ++i){
for(int w=0; w<Kmax; w++) for(int j=0; j<Pmax; j++) acum[w][j] = 0;
for(int k=1; k<K; k++){
for(int rest=0; rest<P; ++rest){
if (dp[k][rest] == 0) continue;
acum[k+1][ (rest+(a[i]%P)) % P ] = max(dp[k+1][ (rest+(a[i]%P))%P ],dp[k][rest] + a[i]);
}
}
for(int k=2; k<=K; k++){
for(int rest=0; rest<P; rest++){
dp[k][rest] = max(dp[k][rest], acum[k][rest]);
}
}
if (dp[1][ a[i]%P ] == 0) dp[1][ a[i]%P ] = a[i];
if (dp[K][0] != 0) {
ok = 1;
g << dp[K][0] << "\n";
break;
}
}
if (ok == 0) {
g << "-1" << "\n";
}
}
}
int main(){
citeste();
rezolva();
f.close();
g.close();
return 0;
}