Cod sursa(job #785213)

Utilizator vendettaSalajan Razvan vendetta Data 8 septembrie 2012 08:57:19
Problema Tricouri Scor 40
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.75 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);
    int s = 0;
    //for(int i=1; i<=n; ++i) cout <<a[i] << " ", s+=a[i], cout << s << "\n";
}

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;
        int Max = 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] << " " <<i << "\n";
                Max = max(Max, dp[K][0]);
            }
        }
        if (ok == 0) {
            g << "-1" << "\n";
        }else g << Max << "\n";
    }

}

int main(){

    citeste();
    rezolva();

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

    return 0;

}