Cod sursa(job #3226442)

Utilizator razvan242Zoltan Razvan-Daniel razvan242 Data 21 aprilie 2024 14:27:20
Problema Problema rucsacului Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include <fstream>
#include <iostream>

using namespace std;

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

const int NMAX = 5001;
const int GMAX = 10001;

struct Obiect {
    int weight, profit;
};

int n, maximumWeight;
Obiect a[NMAX];
int dp[3][GMAX];

void readData() {
    fin >> n >> maximumWeight;
    int x, y;

    for (int i = 1; i <= n; ++i) {
        fin >> x >> y;
        a[i] = {x, y};
    }
}

void solveKnapsack() {
    int row = 1, otherRow;
    for (int i = 1; i <= n; ++i) {
        otherRow = 3 - row;
        for (int w = 0; w <= maximumWeight; ++w) {
            if (a[i].weight > w) {
                dp[row][w] = dp[otherRow][w];
            }
            else {
                dp[row][w] = max(dp[otherRow][w - a[i].weight] + a[i].profit, dp[otherRow][w]);
            }
        }
        row = otherRow;
    }
}

int main() {
    readData();
    solveKnapsack();
    if (n % 2 == 1) {
        fout << dp[1][maximumWeight] << '\n';
    }
    else {
        fout << dp[2][maximumWeight] << '\n';
    }
    return 0;
}