Cod sursa(job #1586715)

Utilizator SmarandaMaria Pandele Smaranda Data 1 februarie 2016 16:47:43
Problema Zebughil Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.19 kb
#include <cstdio>
#include <queue>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 17, inf = (1ll << 31) - 1;
int n, G, g [N + 3], dp [(1 << N) + 6], liber [(1 << N) + 6];
queue <int> q;
bool used [(1 << N) + 6];

void read () {
    int i;
    scanf ("%d%d", &n, &G);

    for (i = 0; i < n; i ++)
        scanf ("%d", &g [i]);
}

void solve () {
    int i, config, config2, lim;
    bool ok;

    lim = (1 << n);
    memset (used, 0, sizeof (used));
    for (i = 0; i < lim; i ++)
        dp [i] = inf;
    for (i = 0; i < n; i ++) {
        config = (1 << i);
        dp [config] = 1;
        liber [config] = G - g [i];
        used [config] = true;
        q.push (config);
    }

    while (!q.empty ()) {
        config = q.front ();
        for (i = 0; i < n; i ++) {
            config2 = config | (1 << i);
            ok = 0;
            if (liber [config] >= g [i]) {
                if (dp [config2] > dp [config]) {
                    dp [config2] = dp [config];
                    ok = 1;
                    liber [config2] = liber [config] - g [i];
                }
                else
                    if (dp [config2] == dp [config]) {
                        liber [config2] = max (liber [config2], liber [config] - g [i]);
                        ok = 1;
                    }
            }
            if (dp [config2] > dp [config] + 1) {
                dp [config2] = dp [config] + 1;
                liber [config2] = G - g [i];
                ok = 1;
            }
            else
                if (dp [config2] == dp [config] + 1) {
                    liber [config2] = max (liber [config2], G - g [i]);
                    ok = 1;
                }
            if (ok == 1)
                if (!used [config2]) {
                    q.push (config2);
                    used [config2] = true;
                }
        }
        q.pop ();
    }
    printf ("%d\n", dp [lim - 1]);
}

int main () {
    int t;

    freopen ("zebughil.in", "r", stdin);
    freopen ("zebughil.out", "w", stdout);

    for (t = 1; t <= 3; t ++) {
        read ();
        solve ();
    }
    return 0;
}