Cod sursa(job #3357547)

Utilizator rapidu36Victor Manz rapidu36 Data 11 iunie 2026 10:44:21
Problema Problema rucsacului Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.81 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 <int> profit(k+1, -1);
    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 (int j = 1; j <= k; j++) {
        profit_max = max(profit_max, profit[j]);
    }
    out << profit_max << "\n";
    out.close();
    return 0;
}