Cod sursa(job #2742840)

Utilizator pibogaBogdan piboga Data 21 aprilie 2021 22:59:36
Problema Problema rucsacului Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.94 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];

    fout << solution;
    return 0;
}