Cod sursa(job #3229043)

Utilizator AztecaVlad Tutunaru 2 Azteca Data 13 mai 2024 12:35:25
Problema Zebughil Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.53 kb
#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

const int N = 17;
const int INF = 1e9;
int g;

struct state {
    int cnt, add;
    bool operator < (const state &other) const {
        if (cnt != other.cnt) {
            return cnt < other.cnt;
        } else {
            return add < other.cnt;
        }
    };
    state operator + (const state &other) const {
        state ret;
        ret.cnt = cnt + other.cnt;
        if (add + other.add > g) {
            ret.cnt++;
            ret.add = add + other.add - g;
        } else {
            ret.add = add + other.add;
        }
        return ret;
    };
};

state dp[1 << N];

int n, z[N];

void solve() {
    cin >> n >> g;
    for (int i = 0; i < n; ++i) {
        cin >> z[i];
    }
    dp[0] = {0, 0};
    for (int mask = 1; mask < (1 << n); mask++) {
        ll sum = 0;
        for (int i = 0; i < n; i++) {
            if ((mask >> i) & 1) {
                sum += z[i];
            }
        }
        dp[mask] = {sum / g, sum % g};

        for (int i = 0; i < n; i++) {
            if ((mask >> i) & 1) {
                dp[mask] = std::min(dp[mask], dp[(1 << i)] + dp[mask ^ (1 << i)]);
            }
        }
    }

    state s = dp[(1 << n) - 1];
    if (s.add != 0) {
        s.cnt++;
    }
    std::cout << s.cnt << '\n';
}

int main() {
    freopen("zebughil.in", "r", stdin);
    freopen("zebughil.out", "w", stdout);
    int t = 3;
    while (t--) {
        solve();
    }
    return 0;
}