Cod sursa(job #2080402)

Utilizator SlevySlevoaca Stefan-Gabriel Slevy Data 2 decembrie 2017 22:05:05
Problema Problema rucsacului Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
#include <iostream>
#include <fstream>
#define NMAX 5001
#define GMAX 10001
#define weight first
#define profit second
#define UNDEF -1

using namespace std;

pair<int, int> objs[NMAX];
int dp[GMAX], n, G;

void read() {

    int x, y;

    ifstream in("rucsac.in");
    in >> n >> G;

    for (int i = 1; i <= n; i++) {

        in >> x >> y;
        objs[i] = make_pair(x, y);
    }
    in.close();
}

int main()
{
    read();

    int maxG = 0;

    for (int i = 1; i <= G; i++)
        dp[i] = UNDEF;

    for (int i = 1; i <= n; i++)
        for (int j = maxG; j >= 0; j--) {
            if (dp[j] != UNDEF) {

                if (objs[i].weight + j <= G && dp[objs[i].weight + j] < dp[j] + objs[i].profit) {

                    dp[objs[i].weight + j] = dp[j] + objs[i].profit;

                    if (maxG < j + objs[i].weight)
                        maxG = j + objs[i].weight;
                }
            }
        }

    int total_profit = 0;

    for (int i = 1; i <= G; i++)
        total_profit = max(total_profit, dp[i]);

    ofstream out("rucsac.out");
    out << total_profit << "\n";
    out.close();

    return 0;
}