Cod sursa(job #785222)

Utilizator vendettaSalajan Razvan vendetta Data 8 septembrie 2012 10:11:06
Problema Tricouri Scor 30
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.93 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], mat[Pmax][Kmax];

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);
    int s = 0;
    //for(int i=1; i<=n; ++i) cout <<a[i] << " ", s+=a[i], cout << s << "\n";
}

void preprocesare(){

    int K = 5;

    for(int P=2; P<Pmax-1; P++){
            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=1; 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];

                for(int x=1; x<=K; x++)mat[P][x] = max(dp[x][0], mat[P][x]);
            }
    }

}

void rezolva(){

    //dp[k][p] = suma obtinuta avand k elemente care dau restul p

    preprocesare();

    for(int i=1; i<=m; i++){
        int K, P;
        f >> K >> P;
        if (mat[P][K] == 0){
            g << "-1" << "\n";
        }else g << mat[P][K] << "\n";
    }

}

int main(){

    citeste();
    rezolva();

    f.close();
    g.close();

    return 0;

}