Cod sursa(job #1674934)

Utilizator penetavyPene Cosmin-Octavian penetavy Data 4 aprilie 2016 22:52:09
Problema Energii Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.42 kb
#include <stdio.h>

FILE *fin = fopen("energii.in", "r");
FILE *fout = fopen("energii.out", "w");


int s[5002];

int main(){
    int G, W;
    int i, j, maxm, minm, cant, cost;
    fscanf(fin, "%d", &G);
    fscanf(fin, "%d", &W);
    maxm = 0;
    s[W] = 999999999;
    for(i = 1; i <= G; i++){
        fscanf(fin, "%d %d", &cant, &cost);

        for(j = maxm; j >= 1; j--)
            if(s[j]){
                if(j + cant >= W){
                    if(s[W] > s[j] + cost)
                        s[W] = s[j] + cost;
                    maxm = W;
                }
                else{
                    if(s[j + cant] == 0)
                        s[j + cant] = s[j] + cost;
                    else if(s[j + cant] > s[j] + cost)
                        s[j + cant] = s[j] + cost;
                    if(maxm < j + cant)
                        maxm = j + cant;
                }
            }
        if(cant >= W){
            if(s[W] > cost)
                s[W] = s[j] + cost;
            maxm = W;
        }
        else{
            if(s[cant] == 0)
                s[cant] = cost;
            else if(s[cant] > cost)
                s[cant] = cost;
            if(maxm < cant)
                maxm = cant;
        }
    }

    if(s[W] == 999999999)
        fprintf(fout, "-1\n");
    else
        fprintf(fout, "%d\n", s[W]);

    fclose(fin);
    fclose(fout);
    return 0;
}