Cod sursa(job #1548887)

Utilizator TopiAlexTopala Alexandru TopiAlex Data 11 decembrie 2015 16:36:24
Problema Energii Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.35 kb
#include <stdio.h>
#define N_MAX 1003
#define MINUS_INFINIT -1

FILE *f, *g;

struct Generator{
    int e;
    int c;
};

int n;
int W;
Generator gen[N_MAX];
int cost[N_MAX];

void citire();
inline void init();

int main()
{
    citire();
    init();
    int i, j;

    for (i = 1; i <= n; ++i){
        for (j = W; j >= 1; --j){
            if (cost[j] != -1){
                if (j + gen[i].e >= W){
                    if (cost[W] == MINUS_INFINIT || cost[W] > cost[j] + gen[i].c){
                        cost[W] = cost[j] + gen[i].c;
                    }
                }else {
                    if (cost[j + gen[i].e] > cost[j] + gen[i].c || cost[j + gen[i].e] == MINUS_INFINIT){
                        cost[j + gen[i].e] = cost[j] + gen[i].c;
                    }
                }
            }
        }
        if (cost[gen[i].e] > gen[i].c || cost[gen[i].e] == MINUS_INFINIT)
            cost[gen[i].e] = gen[i].c;
    }

    fprintf(g, "%d\n", cost[W]);

    fclose(f);
    fclose(g);

    return 0;
}

void citire(){
    f = fopen("energii.in", "r");
    g = fopen("energii.out", "w");

    fscanf(f, "%d%d", &n, &W);

    for (int i = 1; i <= n; ++i)
        fscanf(f, "%d%d", &gen[i].e, &gen[i].c);
}

inline void init(){
    for (int i = 1; i <= W; ++i){
        cost[i] = MINUS_INFINIT;
    }
}