Cod sursa(job #3357546)

Utilizator rapidu36Victor Manz rapidu36 Data 11 iunie 2026 10:37:32
Problema Problema rucsacului Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.92 kb
#include <fstream>
#include <vector>

using namespace std;

struct obiect {
    int g, p;
};

int main() {
    ifstream in("rucsac.in");
    ofstream out("rucsac.out");
    int n, k;
    in >> n >> k;
    vector <obiect> v(n);
    for (int i = 0; i < n; i++) {
        in >> v[i].g >> v[i].p;
    }
    in.close();
    vector <vector <int>> profit(n, vector<int>(k+1));
    profit[0].resize(k+1, -1);
    profit[0][0] = 0;
    if (v[0].g <= k) {
        profit[0][v[0].g] = v[0].p;
    }
    for (int i = 1; i < n; i++) {
        profit[i] = profit[i-1];
        for (int j = v[i].g; j <= k; j++) {
            if (profit[i-1][j-v[i].g] != -1) {
                profit[i][j] = max(profit[i][j], profit[i-1][j-v[i].g] + v[i].p);
            }
        }
    }
    int profit_max = -1;
    for (int j = 1; j <= k; j++) {
        profit_max = max(profit_max, profit[n-1][j]);
    }
    out << profit_max << "\n";
    out.close();
    return 0;
}