Cod sursa(job #2930448)

Utilizator andrei0simionAndrei Simion andrei0simion Data 28 octombrie 2022 14:30:40
Problema Problema rucsacului Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <iostream>
#include <fstream>

using namespace std;

struct obiect
{
    int greutate;
    int profit;
};

int main()
{
    ifstream in("rucsac.in");
    cin.rdbuf(in.rdbuf());
    ofstream out("rucsac.out");
    cout.rdbuf(out.rdbuf());

    int nrObiecte;
    cin >> nrObiecte;
    int greutateMax;
    cin >> greutateMax;

    obiect* obiecte = new obiect[nrObiecte];
    for(int i = 0; i < nrObiecte; i++)
    {
        cin >> obiecte[i].greutate;
        cin >> obiecte[i].profit;
    }

    int* profitMax = new int[greutateMax + 1];
    profitMax[0] = 0;
    for(int i = 1; i < greutateMax + 1; i++)
    {
        profitMax[i] = -1;
    }

    for(int i = 0; i < nrObiecte; i++)
    {
        obiect obj = obiecte[i];
        for(int o = greutateMax + 1 - obj.greutate - 1; o >= 0; o--)
        {
            if(profitMax[o] == -1)
                continue;

            if(profitMax[o + obj.greutate] <= profitMax[o] + obj.profit)
                profitMax[o + obj.greutate] = profitMax[o] + obj.profit;
        }
    }

    int profitMaxim = 0;
    for(int i = 0; i < greutateMax + 1; i++)
    {
        if(profitMax[i] > profitMaxim)
            profitMaxim = profitMax[i];
    }
    cout << profitMaxim << endl;

    delete[] obiecte;
    delete[] profitMax;
    return 0;
}