Pagini recente » Cod sursa (job #2174480) | Cod sursa (job #2624933) | Diferente pentru problema/vecini3 intre reviziile 29 si 12 | Cod sursa (job #1980339) | Cod sursa (job #3318254)
#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;
}