Pagini recente » Cod sursa (job #1851984) | Cod sursa (job #1485820) | Cod sursa (job #65316) | Cod sursa (job #3229506) | Cod sursa (job #3192609)
#include<bits/stdc++.h>
using namespace std;
ifstream f("rucsac.in");
ofstream g("rucsac.out");
int n,G,step,ans;
vector<int>weight,profit;
vector<vector<int>>dp;
int main()
{
f>>n>>G;
dp.assign(2,vector<int>(G+1,-1));
weight.resize(n+1);
profit.resize(n+1);
for(int i=1; i<=n; i++)
f>>weight[i]>>profit[i];
step=0;
dp[0][0]=0;
dp[1][0]=0;
for(int i=1; i<=n; i++,step=1-step)
{
/// we calculate step based on 1-step
dp[step].assign(G+1,-1);
for(int j=0; j<=G; j++)
{
if(dp[1-step][j]>=0)
dp[step][j]=dp[1-step][j]; /// we don't use object i
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]; /// we use object i
}
}
step=1-step;
for(int i=1; i<=G; i++)
ans=max(ans,dp[step][i]);
g<<ans;
return 0;
}