Cod sursa(job #2642979)

Utilizator cyg_vladioanBirsan Vlad cyg_vladioan Data 18 august 2020 00:01:10
Problema Zebughil Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.11 kb
#include <cstdio>
#include <queue>
#include <algorithm>
#include <vector>
#define bm first
#define cst second
using namespace std;
const int NMAX = 17;
const int INF = 2.e9;
vector <int> z , z1;
struct zebughil
{
    int bm , cst;
    zebughil(int x = 0 , int y = 0)
    {
        bm = x;
        cst = y;
    }
};
bool operator<(zebughil a , zebughil b)
{
    return a.cst > b.cst;
}
long long v[NMAX + 5] , G;
int d[(1 << 17) + 5] , n;
void backt(int start , int g , int bm)
{
    for(int i = start ; i <= n ; i ++)
    {
        if(g + v[i] < G && i < n)
            backt(i + 1 , g + v[i] , bm|(1<<(i - 1)));
        if(g + v[i] == G || (i == n && g + v[i] < G))
        {
            z1.push_back(bm | (1 << (i - 1)));
            continue;
        }
        if(g + v[i] > G || i == n)
            z1.push_back(bm);
    }
}
int main()
{
    freopen("zebughil.in" , "r" , stdin);
    freopen("zebughil.out" , "w" , stdout);
    int i , t , lim , bm , new_bm , cst;
    for(t = 1 ; t <= 3 ; t ++)
    {
        scanf("%d%lld" , &n , &G);
        for(i = 1 ; i <= n ; i ++)
            scanf("%lld" , &v[i]);
        sort(v + 1 , v + n + 1);
        backt(1 , 0 , 0);
        for(i = 0 ; i < z1.size() ; i ++)
          if(find(z.begin() , z.end() , z1[i]) == z.end())
            z.push_back(z1[i]);
        lim = (1 << n) - 1;
        for(i = 1 ; i <= lim ; i ++)
            d[i] = INF;
        priority_queue <zebughil> pq;
        pq.push({0 , 0});
        while(!pq.empty())
        {
            bm = pq.top().bm;
            cst = pq.top().cst;
            pq.pop();
            if(bm == lim)
            {
                printf("%d\n" , cst);
                break;
            }
            if(d[bm] < cst)
                continue;
            for(i = 0 ; i < z.size() ; i ++)
            {
                new_bm = (bm | z[i]);
                if(cst + 1 < d[new_bm])
                {
                    d[new_bm] = cst + 1;
                    pq.push({new_bm , cst + 1});
                }
            }
        }
        z.clear();
    }
    return 0;
}