Cod sursa(job #3204109)

Utilizator alexsimedreaAlexandru Simedrea alexsimedrea Data 15 februarie 2024 17:57:37
Problema Problema rucsacului Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.94 kb
#include <iostream>
#include <fstream>
#include <vector>

int findRucsac(int targetWeight, int weights[], int values[], int n) {
    int i, w;
    std::vector<std::vector<int>> K(n + 1, std::vector<int>(targetWeight + 1));

    for (i = 0; i <= n; i++) {
        for (w = 0; w <= targetWeight; w++) {
            if (i == 0 || w == 0) {
                K[i][w] = 0;
            } else if (weights[i - 1] <= w) {
                K[i][w] = std::max(values[i - 1] + K[i - 1][w - weights[i - 1]], K[i - 1][w]);
            } else {
                K[i][w] = K[i - 1][w];
            }
        }
    }
    return K[n][targetWeight];
}

int main() {
    std::ifstream fin("rucsac.in");
    std::ofstream fout("rucsac.out");

    int values[5005], weights[5005];
    int n, targetWeight;

    fin >> n >> targetWeight;
    for (int i = 0; i < n; ++i) {
        fin >> weights[i] >> values[i];
    }

    fout << findRucsac(targetWeight, weights, values, n);
    return 0;
}