Cod sursa(job #2585693)

Utilizator rapidu36Victor Manz rapidu36 Data 19 martie 2020 12:24:43
Problema Problema rucsacului Scor 100
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <stdio.h>
#include <stdlib.h>
#define N 5000
#define G 10001
#define INF 10001

typedef struct
{
    int g, p;
} obiect;

obiect v[N];
int profit[G];

FILE *in, *out;

int main()
{
    in = fopen("rucsac.in", "r");
    out = fopen("rucsac.out", "w");
    int i, j, n, k;
    fscanf(in, "%d%d", &n, &k);
    for (i = 0; i < n; i++)
    {
        fscanf(in, "%d%d", &v[i].g, &v[i].p);
    }
    fclose(in);
    ///initializez vectorul profit
    for (j = 1; j <= k; j++)
    {
        profit[j] = -INF;
    }
    for (i = 0; i < n; i++)
    {
        ///actualizez vectorul de configuratii profit, folosind obiectul i
        for (j = k - v[i].g; j >= 0; j--)
        {
            ///j = configuratia la care adaug obiectul curent i
            if (profit[j] != -INF)
            {
                if (profit[j] + v[i].p > profit[j + v[i].g])
                {
                    profit[j + v[i].g] = profit[j] + v[i].p;
                }
            }
        }
    }
    ///calculez rezultatul final (max din vectorul profit)
    int rez = -INF;
    for (j = 1; j <= k; j++)
    {
        if (profit[j] > rez)
        {
            rez = profit[j];
        }
    }
    fprintf(out, "%d", rez);
    fclose(out);
    return 0;
}