Cod sursa(job #3354579)

Utilizator leoebunLeonard Neacsa leoebun Data 19 mai 2026 09:20:36
Problema Problema rucsacului Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.94 kb
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <fstream>

using namespace std;


int main() {

    std::ios::sync_with_stdio(false);

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

    int n, w;

    fin >> n >> w;

    vector<pair<int, int>> items;
    items.push_back({0, 0});
    for (int i = 0; i < n; i++) {
        int x, y;
        fin >> x >> y;
        items.push_back({x, y});
    }

    vector<vector<int>> dp(n + 1, vector<int>(w + 1, 0));

    for (int i = 1; i <= n; i++) {
        auto [weight, price] = items[i];
        for (int j = 1; j <= w; j++) {
            int x = j - weight;
            if (x >= 0) {
                dp[i][j] = dp[i - 1][x] + price;
            }

            dp[i][j] = max(dp[i][j], dp[i - 1][j]);
            dp[i][j] = max(dp[i][j], dp[i][j - 1]);
        }
    }


    fout << dp[n][w] << ' ';

    fin.close();
    fout.close();
    return 0;
}