Cod sursa(job #3241286)

Utilizator SilviuC25Silviu Chisalita SilviuC25 Data 28 august 2024 15:48:44
Problema Problema rucsacului Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1 kb
#include <bits/stdc++.h>
using namespace std;

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

const int MAX_WEIGHT = 1e4 + 5;
const int MAX_OBJECTS = 1e4 + 5;

int n, g;
int w[MAX_OBJECTS], p[MAX_OBJECTS], maxProfit[MAX_WEIGHT][MAX_OBJECTS];
int answer;

int solve(int weight, int index) {
    if (index > n || weight > g) {
        return 0;
    }
    if (maxProfit[weight][index] != -1) {
        return maxProfit[weight][index];
    }
    int profit = solve(weight, index + 1), currentProfit = 0, newWeight = weight + w[index];
    if (newWeight <= g) {
        currentProfit = p[index] + solve(newWeight, index + 1);
    }
    maxProfit[weight][index] = max(profit, currentProfit);
    return maxProfit[weight][index];
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    fin >> n >> g;
    for (int i = 1; i <= n; ++i) {
        fin >> w[i] >> p[i];
    }
    memset(maxProfit, -1, sizeof(maxProfit));
    cout << solve(0, 0);
    return 0;
}