Pagini recente » Cod sursa (job #1340873) | Cod sursa (job #2314063) | Cod sursa (job #161370) | Cod sursa (job #2071444) | Cod sursa (job #3318277)
#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];
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;
return 0;
}