Cod sursa(job #3309144)

Utilizator alesiodemiriAlesio Demiri alesiodemiri Data 1 septembrie 2025 21:16:02
Problema Problema rucsacului Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <iostream>
#include <queue>
#include <algorithm>
#include <set>
#include <map>
#include <stack>
#include <vector>
#include <string>
#include <deque>
#include <unordered_map>
#include <unordered_set>
#include <cmath>
#include <iomanip>

using namespace std;

#define ll long long

int n, capacity;
vector<int> weights, profits;

void ReadData() {
    cin >> n >> capacity;
    int val = 0;
    for(int i = 0; i < n; ++i){
        cin >> val;
        weights.push_back(val);
        cin >> val;
        profits.push_back(val);
    }
}

int dfs(int index, int cap){
    if(index == n) return 0;
    if (cap >= weights[index]){
        int left = profits[index] + dfs(index + 1, cap - weights[index]);
        int right = dfs(index + 1, cap);
        return max(left, right);
    }
    return dfs(index + 1, cap);
}

void Solve() {
    vector<vector<int>> dp(n + 1, vector<int>(capacity + 1, 0));

    for(int i = 1; i <= n; i++){
        for(int c = 0; c <= capacity; c++){
            dp[i][c] = dp[i - 1][c];
            if (weights[i-1] <= c)
                dp[i][c] = max(dp[i - 1][c], profits[i - 1] + dp[i - 1][c - weights[i - 1]]); 
        }
    }

    cout << dp[n][capacity] << "\n";
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    freopen("rucsac.in", "r", stdin);
    freopen("rucsac.out", "w", stdout);

    int t = 1;
    // cin >> t; // Uncomment for multiple test cases
    while (t--) {
        ReadData();
        Solve();   
    }
    return 0;
}