Cod sursa(job #421114)

Utilizator DraStiKDragos Oprica DraStiK Data 21 martie 2010 10:39:49
Problema Tricouri Scor 30
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.74 kb
#include <algorithm>
#include <set>
using namespace std;

#define DIM 25
#define MAX 5

struct cmp
{
    bool operator () (const int &a,const int &b) const
    {
        return a>b;
    }
}; set <int,cmp> g[DIM][DIM];
int n,m,k,p,nrmax;
int f[DIM];

void read ()
{
    set <int> :: iterator it;
    int i,j,x;

    scanf ("%d%d",&n,&m);
    for (i=1; i<=n; ++i)
    {
        scanf ("%d",&x);
        for (j=2; j<DIM; ++j)
        {
            g[j][x%j].insert (x);
            if (g[j][x%j].size ()>MAX)
            {
                it=g[j][x%j].end ();
                g[j][x%j].erase (--it);
            }
        }
    }
}

inline void check_solve (int sumcur)
{
    set <int> :: iterator it;
    int i,j,nrc;

    ++f[(p-sumcur%p)%p];
    for (nrc=0, i=0; i<p; ++i)
        if (f[i]>(int)g[p][i].size ())
        {
            --f[(p-sumcur%p)%p];
            return ;
        }
        else
            for (j=1, it=g[p][i].begin (); j<=f[i] && it!=g[p][i].end (); ++j, ++it)
                nrc+=*it;
    --f[(p-sumcur%p)%p];
    nrmax=max (nrmax,nrc);
}

void back (int step,int start,int sumcur)
{
    int i;

    if (step==k)
        check_solve (sumcur);
    else
        for (i=start; i<p; ++i)
        {
            ++f[i];
            back (step+1,i,sumcur+i);
            --f[i];
        }
}

void solve ()
{
    int i;

    for (i=1; i<=m; ++i)
    {
        scanf ("%d%d",&k,&p);
        nrmax=0;
        back (1,0,0);
        if (nrmax)
            printf ("%d\n",nrmax);
        else
            printf ("-1\n");
    }
}

int main ()
{
    freopen ("tricouri.in","r",stdin);
    freopen ("tricouri.out","w",stdout);

    read ();
    solve ();

    return 0;
}