Cod sursa(job #785205)

Utilizator vendettaSalajan Razvan vendetta Data 8 septembrie 2012 08:31:28
Problema Tricouri Scor 20
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.3 kb
#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];

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<=K; w++) for(int j=0; j<=P; j++) dp[w][j] = 0;
        dp[1][ a[1]%P ] = a[1];
        for(int i=2; i<=n; ++i){
            for(int k=1; k<=K; k++){
                for(int rest=0; rest<P; ++rest){
                    if (dp[k][rest] == 0) continue;
                    dp[k+1][ (rest+(a[i]%P)) % P ] = dp[k][rest] + a[i];
                }
            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;

}