Cod sursa(job #785211)

Utilizator vendettaSalajan Razvan vendetta Data 8 septembrie 2012 08:43:03
Problema Tricouri Scor 20
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.63 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], 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=0; 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=0; k<=K; k++){
                for(int rest=0; rest<P; rest++){
                    dp[k][rest] = max(dp[k][rest], acum[k][rest]);
                    acum[k][rest] = 0;
                }
            }
            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;

}