Cod sursa(job #995159)

Utilizator gbi250Gabriela Moldovan gbi250 Data 7 septembrie 2013 19:32:04
Problema Energii Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.05 kb
#include <cstdio>

using namespace std;

int i, g, W, cw, sum, MIN=0x3f3f3f3f, energy[1001], cost[1001], cst[2][5001];


int main()
{
    freopen("energii.in", "r", stdin);
    freopen("energii.out", "w", stdout);
    scanf("%d %d", &g, &W);

    for(i=1; i<=g; ++i)
        scanf("%d %d", &energy[i], &cost[i]), sum+=energy[i];
    for(cw=0; cw<=W; ++cw)
        cst[0][cw]=cst[1][cw]=0x3f3f3f3f;
    cst[0][0]=0;
    if(sum<W)
        printf("-1\n");
    else
    {
        for(i=1; i<=g; ++i)
            for(cw=0; cw<=W; ++cw)
            {
                if(cw + energy[i] >= W)
                    if(MIN > cst[1-i%2][cw] + cost[i])
                        MIN = cst[1-i%2][cw] + cost[i];

                cst[i%2][cw]=cst[1-i%2][cw];
                if(cw >= energy[i])
                    if(cst[i%2][cw] > cst[1-i%2][cw - energy[i]] + cost[i])
                        cst[i%2][cw] = cst[1-i%2][cw - energy[i]] + cost[i];
            }
        if(MIN != 0x3f3f3f3f)
            printf("%d\n", MIN);
        else
            printf("-1\n");
    }
    return 0;
}