Cod sursa(job #3200602)

Utilizator rapidu36Victor Manz rapidu36 Data 5 februarie 2024 11:35:45
Problema Problema rucsacului Scor 100
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include <stdio.h>
#include <stdlib.h>
#define N 5000
#define K 10000

int profit[K+1], g[N], p[N];

int max(int a, int b)
{
    return (a > b ? a : b);
}

int main()
{
    FILE *in, *out;
    in = fopen("rucsac.in", "r");
    out = fopen("rucsac.out", "w");
    int n, k;
    fscanf(in, "%d%d", &n, &k);
    for (int i = 0; i < n; i++)
    {
        fscanf(in, "%d%d", &g[i], &p[i]);
    }
    ///initializam elem. vectorului profit
    for (int j = 1; j <= k; j++)
    {
        profit[j] = -1;///nu exista multime de obiecte cu suma gr. j
    }
    profit[0] = 0;///putem adauga orice obiect la "nimic"
    ///si "nimic" ne aduce profitul 0
    for (int i = 0; i < n; i++)
    {
        for (int j = k - g[i]; j >= 0; j--)///adunand g[i] nu depasim k
        {
            if (profit[j] != -1)///daca folosind ob. 0,..., i-1 putem obtine gr. j
            {
                profit[j+g[i]] = max(profit[j+g[i]], profit[j] + p[i]);
            }
        }
    }
    int profit_max = -1;
    for (int j = 1; j <= k; j++)
    {
        profit_max = max(profit_max, profit[j]);
    }
    fprintf(out, "%d\n", profit_max);
    fclose(in);
    fclose(out);
    return 0;
}