Cod sursa(job #3358697)

Utilizator rapidu36Victor Manz rapidu36 Data 19 iunie 2026 16:11:06
Problema Problema rucsacului Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.78 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);
    vector <int> profit(k + 1, -1);
    for (auto &ob: v) {
        in >> ob.g >> ob.p;
    }
    in.close();
    profit[0] = 0;
    if (v[0].g <= k) {
        profit[v[0].g] = v[0].p;
    }
    for (int i = 1; i < n; i++) {
        for (int j = k; j >= v[i].g; j--) {
            if (profit[j-v[i].g] != -1) {
                profit[j] = max(profit[j], profit[j-v[i].g] + v[i].p);
            }
        }
    }
    int profit_max = -1;
    for (auto p: profit) {
        profit_max = max(profit_max, p);
    }
    out << profit_max << "\n";
    out.close();
    return 0;
}