Cod sursa(job #3174408)

Utilizator radu._.21Radu Pelea radu._.21 Data 24 noiembrie 2023 18:52:26
Problema Zebughil Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.38 kb
#include <fstream>
#include <cstring>
#include <algorithm>

using namespace std;
ifstream fin("zebughil.in");
ofstream fout("zebughil.out");
unsigned int dp[1 << 17];
unsigned int best[1 << 17];
unsigned int sum[1 << 17];
unsigned int v[17];
int n, G;
int main()
{


    for (int q = 0;q < 3;q++) {
        fin>>n>>G;
        for (int i=0;i<n;i++) {
            fin>>v[i];
            sum[(1<<i)]=v[i];
        }
        unsigned int total, sumLeft;
        for (int i = 1;i < (1 << n);i++) {
             sum[i] =sum[i^(i&-i)]+sum[i&-i]>G ? G+1:sum[i^(i&-i)]+sum[i&-i];
             if (sum[i]<=G) {
                dp[i]=G-sum[i];
                best[i]=1;
                continue;
             }
            best[i]=n+1;
             for (int j=0;j<n;j++) {
                if ((i>>j)&1) {
                    total = best[i^(1<<j)];
                    if (v[j]>dp[i^(1<<j)]) {
                        total++;
                        sumLeft = G - v[j];
                    } else {
                        sumLeft = dp[i^(1<<j)]-v[j];
                    }
                    if (total < best[i] || (total == best[i] && sumLeft > dp[i])) {
                       best[i] = total;
                        dp[i] = sumLeft;
                    }
                }
             }
        }
        fout << best[(1<< n)-1] << "\n";
    }
    return 0;
}