Cod sursa(job #3184460)

Utilizator mirceamaierean41Mircea Maierean mirceamaierean41 Data 16 decembrie 2023 00:46:40
Problema Problema rucsacului Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.81 kb
#include <fstream>
#include <string.h>
using namespace std;

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

int n, g, w, p;

const int WMAX = 1e4 + 1;
int dp[2][WMAX];

int main()
{
    fin >> n >> g;
    memset(dp, -1, sizeof(dp));
    dp[1][0] = 0;
    dp[0][0] = 0;
    int vMax = 0;
    for (int i = 0; i < n; ++i)
    {
        int crtIndex = i % 2, antIndex = 1 - crtIndex;
        fin >> w >> p;
        for (int j = 0; j <= g; ++j)
        {
            dp[crtIndex][j] = dp[antIndex][j];
            int prev = j - w;

            if (prev >= 0 && dp[antIndex][prev] != -1 && dp[antIndex][prev] + p > dp[crtIndex][j])
                dp[crtIndex][j] = dp[antIndex][prev] + p;

            if (dp[crtIndex][j] > vMax)
                vMax = dp[crtIndex][j];
        }
    }
    fout << vMax << '\n';
    return 0;
}