Cod sursa(job #3221440)

Utilizator RobertAcAcatrinei Robert-Marian RobertAc Data 7 aprilie 2024 10:42:10
Problema Zebughil Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.96 kb
#include <bits/stdc++.h>
#ifdef LOCAL
#define in cin
#define out cout
#endif

using namespace std;

#ifndef LOCAL
ifstream in("zebughil.in");
ofstream out("zebughil.out");
#endif

const int nmax = 18;
const int maskmax = 1 << (nmax);

int g;
int n;

int v[nmax];

struct state
{
    int a, b;
    void reset()
    {
        a = b = 1e9;
    }
    state operator+(const int other)
    {
        auto ret = state{a, b};
        if (b + other > g)
        {
            ret.a++;
            ret.b = 0;
        }
        ret.b += other;
        return ret;
    }
    bool operator<(const state &other) const
    {
        if (a == other.a)
            return b < other.b;
        return a < other.a;
    }
};

state dp[maskmax];

void bkt(int ind, int cnt, int maxx, int mask)
{
    if (ind == n)
        return;
    if (cnt == maxx)
    {
        // bitset<4> b(mask);
        // cerr << b.to_string() << '\n';
        for (int i = 0; i < n; i++)
        {
            if (bool(mask & (1 << i)) == 0)
            {
                // cerr << "avem " << i << '\n';
                int newmask = mask | (1 << i);
                // bitset<4> b(newmask);
                // cerr << "masca " << b.to_string() << '\n';
                dp[newmask] = min(dp[newmask], dp[mask] + v[i]);
            }
        }
    }
    else
    {
        bkt(ind + 1, cnt + 1, maxx, mask | (1 << ind));
        bkt(ind + 1, cnt, maxx, mask);
    }
}

void solve()
{
    for (int i = 0; i < maskmax; i++)
        dp[i].reset();
    in >> n >> g;
    for (int i = 0; i < n; i++)
    {
        in >> v[i];
    }
    dp[0].a = 0;
    dp[0].b = 0;
    for (int i = 0; i < n; i++)
        bkt(0, 0, i, 0);
    int res = (1 << n) - 1;
    if (dp[res].b != 0)
        dp[res].a++;
    for (int i = 0; i <= res; i++)
    {
        bitset<4> b(i);
        // cerr << b.to_string() << ' ' << dp[i].a << ' ' << dp[i].b << '\n';
    }
    out << dp[res].a << '\n';
}

int main()
{
    int t = 3;
    while (t--)
    {
        solve();
    }
}