Cod sursa(job #3155816)

Utilizator RatebaSerbanescu Andrei Victor Rateba Data 9 octombrie 2023 19:36:25
Problema Problema rucsacului Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
#include <fstream>

using namespace std;

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

// 1 ≤ N ≤ 5000
// 1 ≤ G ≤ 10000
// 0 ≤ Wi, Pi ≤ 10000

const int MAX_N = 5005;
const int MAX_G = 10005; 

struct t_obiect {
    int weight;
    int val;
};

int dp[MAX_N][MAX_G];

int main() {

    int nr_elem;
    int weight;
    t_obiect objects[MAX_N];

    fin >> nr_elem >> weight;

    for (int i = 1; i <= nr_elem; i++) {
        int weight;
        int val;

        fin >> weight;
        fin >> val;

        t_obiect ob = {weight, val};
        objects[i] = ob;
    }

    for (int i = 1; i <= nr_elem; i++) {
        for (int w = 0; w <= weight; w++) {

            if (objects[i].weight > w) {
                dp[i][w] = dp[i - 1][w];
            } else {
                int without_object = dp[i - 1][w];
                int with_object = dp[i - 1][w - objects[i].weight] + objects[i].val;

                dp[i][w] = max(without_object, with_object);
            }

        }
    }

    fout << dp[nr_elem][weight];

    return 0;
}