Cod sursa(job #3318254)

Utilizator AndreiCod123Sitaru Mircea AndreiCod123 Data 27 octombrie 2025 17:31:39
Problema Problema rucsacului Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include<bits/stdc++.h>
using namespace std;
ifstream fin("rucsac.in");
ofstream fout("rucsac.out");

int n, g, step, ans, i, j;
vector<int> weight, profit;
vector<vector<int>> dp;

int main()
{
    fin>> n>> g;
    dp.assign(2, vector<int>(g+1, -1));
    weight.resize(n+1);
    profit.resize(n+1);

    for(i = 1; i <= n; i++)
        fin>> weight[i]>> profit[i];

    step = 0;
    dp[0][0] = 0;
    dp[1][0] = 0;

    for(i = 1; i <= n; i++, step = 1-step)
    {
        dp[step].assign(g+1, -1);
        for(j = 0; j <= g; j++)
        {
            if(dp[1-step][j] >= 0)
                dp[step][j] = dp[1-step][j];
            else if(j >= weight[i] && dp[1-step][j-weight[i]] >= 0 &&
                    dp[1-step][j-weight[i]] + profit[i] > dp[step][j])
                        dp[step][j] = dp[1-step][j-weight[i]] + profit[i];
        }
    }

    step = 1-step;
    for(i = 1; i <= g; i++)
        ans = max(ans, dp[step][i]);
    fout<< ans;
    fin.close();
    fout.close();
    return 0;
}