nafeeur10's blog

By nafeeur10, history, 9 years ago, In English

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));


}
  • Vote: I like it
  • +7
  • Vote: I do not like it

| Write comment?
»
9 years ago, # |
  Vote: I like it 0 Vote: I do not like it

I know that if I use pair it will be easy to get two values. But I can't code it.

  • »
    »
    9 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like 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(i == n+1) {
     if(w == CAP) return 0;
     else return -INFINITY;
    }
    
    • »
      »
      »
      9 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      If you want to output both optimal benefit and weight then:

      pair<int,int> func(int i,int w)
      {
          if(i==n+1) return make_pair(0,w);
          if(dp[i][w]!=-1) return dp[i][w];
          pair<int,int> profit1, profit2;
      
          if(w+weight[i]<=CAP) {
              pair<int,int> tmp = func(i+1, w + weight[i]);
              profit1 = make_pair(tmp.first+cost[i], tmp.second);
          }
          else
              profit1 = make_pair(0,0);
      
          profit2=func(i+1,w);
          dp[i][w]=max(profit1,profit2);
          return dp[i][w];
      }
      
      • »
        »
        »
        »
        9 years ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        In this line--- if(dp[i][w]!=-1) return dp[i][w]; you are returning an integer value. Even in last of this function.