0-1 Knapsack: return weight and maximum value in C++

Revision en1, by nafeeur10, 2015-06-10 21:58:34

We know in 0-1 Knapsack problem we get the maximum benefits from some items with a limited capacity. Example:

4 10 // 5 items, 10 capacity
1 120 // weight cost_value
4 280
3 150
4 200
Ans: 600
Total Weight: 9

But my question is, I want the total weight and benefit at a time. How is this possible? And what will be the change of my code? Please suggest me with my own code.

#include <bits/stdc++.h>

using namespace std;

#define MAX_N 100
#define MAX_W 1000
int n;
int dp[MAX_N+1][MAX_W+1];
int weight[MAX_N+1];
int cost[MAX_N+1];
int CAP;
int func(int i,int w)
{
    if(i==n+1) return 0;
    if(dp[i][w]!=-1) return dp[i][w];
    int profit1=0,profit2=0;
    if(w+weight[i]<=CAP)
        profit1=cost[i]+func(i+1,w+weight[i]);

    profit2=func(i+1,w);
    dp[i][w]=max(profit1,profit2);
    return dp[i][w];
}
int main()
{

    //freopen("in","r",stdin);
    memset(dp,-1,sizeof(dp));
    scanf("%d%d",&n,&CAP);
    for(int i=1; i<=n; i++)
    {
        scanf("%d %d",&weight[i],&cost[i]);
    }
    printf("%d\n",func(1,0));


}

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English nafeeur10 2015-06-10 21:58:34 1174 Initial revision (published)