Cod sursa(job #1836881)

Utilizator hantoniusStan Antoniu hantonius Data 28 decembrie 2016 19:36:32
Problema Problema rucsacului Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <fstream>
#define maxn 5002
using namespace std;

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

int n, g, gr[maxn], cost[maxn], best_gr[maxn], best_cost[maxn];

void read()
{
    fin >> n >> g;
    for (int i = 1; i <= n; i++)
        fin >> gr[i] >> cost[i];
}

void solve()
{
    int i, start, maxcost, maxgr;

    for (i = 1; i <= n; i++)
        if (gr[i] <= g)
            break;
    start = i;
    best_gr[i] = gr[i];
    best_cost[i] = cost[i];
    for (i = i + 1; i <= n; i++) {
        maxcost = 0;
        maxgr = 0;
        for (int j = start; j < i; j++)
            if (best_gr[j] + gr[i] <= g && (best_cost[j] + cost[j] > maxcost || best_cost[j] + cost[j] == maxcost && best_gr[j] + gr[i] < maxgr)) {
                maxcost = best_cost[j] + cost[j];
                maxgr = best_gr[j] + gr[i];
            }
            if (maxgr == 0) {
                best_cost[i] = best_cost[i - 1];
                best_gr[i] = best_gr[i - 1];
            }
            else {
                best_cost[i] = maxcost;
                best_gr[i] = maxgr;
            }
    }
}

int main()
{
    read();
    solve();
    fout << best_cost[n];
    return 0;
}