Cod sursa(job #3133640)

Utilizator indibotocIndi Botoc indibotoc Data 26 mai 2023 14:44:11
Problema Problema rucsacului Scor 0
Compilator c-64 Status done
Runda Arhiva educationala Marime 0.99 kb
#include <stdio.h>

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

int knapsack(int n, int masa, int weight[], int profit[])
{
    int kgpret[n+1][masa+1], i, j;
    for(i = 0; i <= n; i++)
        kgpret[i][0] = 0;  /// profit 0 cu 0 obiecte

    for(j = 0; j <= masa; j++)
        kgpret[0][j] = 0; /// profit 0 cu 0 kg limita
    for(i = 1; i <= n; i++)
    {
        for(j = 1; j <= masa; j++)
        {
            if(weight[i-1] <= j)
                kgpret[i][j] = max(kgpret[i-1][j], profit[i-1] + kgpret[i-1][j-weight[i-1]]);
            else
                kgpret[i][j] = kgpret[i-1][j];
        }
    }
    return kgpret[n][masa];
}


int main()
{
    int n;
    int masa;
    scanf("%d%d", &n, &masa);
    int weight[n+1];
    int profit[n+1];
    for(int i=0; i<n; i++)
        scanf("%d%d", &weight[i], &profit[i]);


    int max_profit = knapsack(n, masa, weight, profit);

    printf("Profitul maxim este %d\n", max_profit);

    return 0;
}