Cod sursa(job #1157522)

Utilizator mihai995mihai995 mihai995 Data 28 martie 2014 16:09:04
Problema Zebughil Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.4 kb
#include <fstream>
using namespace std;

const int N = 17;

int cost[N], best[1 << N], unitTrucks[1 + (1 << N)], n, Gmax;

ifstream in("zebughil.in");
ofstream out("zebughil.out");

inline int lsb(int x){
    return x & -x;
}

inline int getCost(int x){
    int ans = 0;
    while (x && ans <= Gmax){
        ans += cost[__builtin_ctz(x)];
        x &= x - 1;
    }
    return ans;
}

int getMinTrucks(int groupA, int groupB, int costB, int poz){
    if (poz == -1)
        return best[groupA] + 1;
    if ( ( groupA & (1 << poz) ) && costB + cost[poz] <= Gmax )
        return min( getMinTrucks(groupA, groupB, costB, poz - 1),
                    getMinTrucks(groupA ^ (1 << poz), groupB ^ (1 << poz), costB + cost[poz], poz - 1) );
    return getMinTrucks(groupA, groupB, costB, poz - 1);
}

int compute(){
    int p;

    in >> n >> Gmax;
    for (int i = 0 ; i < n ; i++)
        in >> cost[i];

    best[0] = 0;
    for (int i = 1, p = 0 ; i < (1 << n) ; i++){
        if ( ( 1 << (p + 1) ) == i )
            p++;
        if ( Gmax < getCost(i) )
            best[i] = getMinTrucks(i ^ (1 << p), 1 << p, cost[p], p - 1);
        else{
            best[i] = 1;
            unitTrucks[ ++unitTrucks[0] ] = i;
        }
    }
    return best[ (1 << n) - 1 ];
}

int main(){
    int times = 3;

    while (times--)
        out << compute() << '\n';

    return 0;
}