Cod sursa(job #3226439)

Utilizator razvan242Zoltan Razvan-Daniel razvan242 Data 21 aprilie 2024 14:19:55
Problema Problema rucsacului Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.83 kb
#include <fstream>

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[NMAX][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() {
    for (int i = 1; i <= n; ++i) {
        for (int w = 0; w <= maximumWeight; ++w) {
            if (a[i].weight > w) {
                dp[i][w] = dp[i - 1][w];
            }
            else {
                dp[i][w] = max(dp[i - 1][w - a[i].weight] + a[i].profit, dp[i - 1][w]);
            }
        }
    }
}

int main() {
    readData();
    solveKnapsack();
    fout << dp[n][maximumWeight] << '\n';
    return 0;
}