C++ Program to Solve the Fractional Knapsack Problem

C++Server Side ProgrammingProgramming

In Fractional knapsack problem, a set of items are given, each with a weight and a value. We need to break items for maximizing the total value of knapsack and this can be done in greedy approach.

Algorithm

Begin
   Take an array of structure Item
   Declare value, weight, knapsack weight and density
   Calculate density=value/weight for each item
   Sorting the items array on the order of decreasing density
   We add values from the top of the array to total value until the bag is full, i.e; total
   value <= W
End

Example Code

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
typedef struct {
   int v;
   int w;
   float d;
} Item;
void input(Item items[],int sizeOfItems) {
   cout << "Enter total "<< sizeOfItems <<" item's values and weight" <<
   endl;
   for(int I = 0; I < sizeOfItems; i++) {
      cout << "Enter "<< i+1 << " V ";
      cin >> items[i].v;
      cout << "Enter "<< i+1 << " W";
      cin >> items[i].w;
   }
}
void display(Item items[], int sizeOfItems) {
   int i;
   cout << "values: ";
   for(i = 0; i < sizeOfItems; i++) {
      cout << items[i].v << "\t";
   }
   cout << endl << "weight: ";
   for (I = 0; I < sizeOfItems; i++) {
      cout << items[i].w << "\t";
   }
   cout << endl;
}
bool compare(Item i1, Item i2) {
   return (i1.d > i2.d);
}
float knapsack(Item items[], int sizeOfItems, int W) {
   int i, j, pos;
   Item mx, temp;
   float totalValue = 0, totalWeight = 0;
   for (i = 0; i < sizeOfItems; i++) {
      items[i].d = items[i].v / items[i].w;
   }
   sort(items, items+sizeOfItems, compare);
   for(i=0; i<sizeOfItems; i++) {
      if(totalWeight + items[i].w<= W) {
         totalValue += items[i].v ;
         totalWeight += items[i].w;
      } else {
         int wt = W-totalWeight;
         totalValue += (wt * items[i].d);
         totalWeight += wt;
         break;
      }
   }
   cout << "total weight in bag " << totalWeight<<endl;
   return totalValue;
}
int main() {
   int W;
   Item items[4];
   input(items, 4);
   cout << "Entered data \n";
   display(items,4);
   cout<< "Enter Knapsack weight \n";
   cin >> W;
   float mxVal = knapsack(items, 4, W);
   cout << "Max value for "<< W <<" weight is "<< mxVal;
}

Output

Enter total 4 item's values and weight
Enter 1 V 50
Enter 1 W 10
Enter 2 V 60
Enter 2 W 20
Enter 3 V 70
Enter 3 W 30
Enter 4 V 70
Enter 4 W 40
Entered data
values: 50 60 70 70
weight: 10 20 30 40
Enter Knapsack weight
60
total weight in bag 60
Max value for 60 weight is 180
raja
Published on 15-Mar-2019 11:33:10
Advertisements