Cod sursa(job #2740315)

Utilizator pibogaBogdan piboga Data 12 aprilie 2021 16:18:55
Problema Problema rucsacului Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.08 kb
#include <fstream>
#include <vector>

using namespace std;

ifstream fin("rucsac.in");
ofstream fout("rucsac.out");

struct Object
{
    int weight, price;
};

int main()
{
    int noObjects = 0, maxWeight = 0;
    fin >> noObjects >> maxWeight;
    vector<Object> objects;

    int *dp = (int *) calloc(maxWeight + 1, sizeof(int));

    for (int idObject = 0; idObject < noObjects; ++idObject)
    {
        Object object{};
        fin >> object.weight >> object.price;
        objects.push_back(object);
    }

    for (int idObject = 0; idObject < noObjects; ++idObject)
    {
        for (int idWeight = maxWeight; idWeight >= objects[idObject].weight; --idWeight)
        {
            int previousWeight = idWeight - objects[idObject].weight;
            dp[idWeight] = max(dp[idWeight], dp[previousWeight] + objects[idObject].price);
        }
    }

    int solution = dp[maxWeight];
    for (int idWeight = maxWeight - 1; idWeight >= 0; --idWeight)
    {
        if (dp[idWeight] > solution)
        {
            solution = dp[idWeight];
        }
    }

    fout << solution;
    return 0;
}