Cod sursa(job #995149)

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

using namespace std;

int i, g, W, cw, sum, MIN=0x3f3f3f3f, energy[1001], cost[1001], cst[1001][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(i=0; i<=g; ++i)
        for(cw=0; cw<=W; ++cw)
            cst[i][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) // posibila solutie
                    if(MIN > cst[i-1][cw] + cost[i]) // daca avem un cost mai mic decat MIN
                        MIN = cst[i-1][cw] + cost[i];

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