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));
}
I know that if I use pair it will be easy to get two values. But I can't code it.
What do you want to do? If you want total weight to be equal to capacity then change "if(i==n+1) return 0;" into:
If you want to output both optimal benefit and weight then:
In this line---
if(dp[i][w]!=-1) return dp[i][w];
you are returning an integer value. Even in last of this function.yep, dp[][] must be of type pair<int,int>. So additionally change -1 into make_pair(-1,-1) or sth similar. Btw. your program never uses computed dp.
I have edited. But weight is not giving. Please check it. http://paste.ubuntu.com/11694690/
You don't change 'w' at all. Change dp into pair<int,int> or don't use dp.
Will you please edit my new code??
here you go