Cod sursa(job #3281979)

Utilizator Cristi1123Lucan Crisitian Cristi1123 Data 4 martie 2025 11:32:44
Problema Problema rucsacului Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.99 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

struct BackpackObj{
    int weight, value;
};

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

    int obj_count, backpack_capacity;
    fin >> obj_count >> backpack_capacity;

    vector<BackpackObj> objects(obj_count);
    for (int i = 0; i < obj_count; ++i)
        fin >> objects[i].weight >> objects[i].value;
    
    vector<vector<int>> dynamic_matrix(obj_count + 1, vector<int>(backpack_capacity + 1));
    // max(backpack without object i, 
    // backpack with object i (which means we take the maximum of the backpack with a decreased capacity))
    for (int i = 1; i <= obj_count; ++i)
        for (int j = 1; j <= backpack_capacity; ++j)
        dynamic_matrix[i][j] = max(dynamic_matrix[i - 1][j],
                                   dynamic_matrix[i - 1][j - objects[i - 1].weight] + objects[i - 1].value);
    
    fout << dynamic_matrix.back().back() << '\n';
}