Question:
How to represent the maximum value in knapsack using C++

Summary

Let’s assume:

Integer- value, weight

Function- fractionalKnapsack


Considering three parameters:

Maximum weight capacity- w

Array of items- a

Number of items- n


Solution


//class implemented

/*

struct Item{

    int value;

    int weight;

};

*/



class Solution

{

    public:

    static bool cmp(pair<double, Item> a, pair<double, Item> b){

        return a.first>b.first;

    }

    //Function to get the maximum total value in the knapsack.

    double fractionalKnapsack(int w, Item a[], int n)

    {

        // Your code here

        vector<pair<double, Item>> v;

        for(int i=0; i<n; i++){

        double perunitvalue=(a[i].value*1.0/a[i].weight);

           v.push_back({perunitvalue, a[i]});

        }

       sort(v.begin(), v.end(), cmp);

       

       double totalvalue=0;

       for(int i=0; i<n; i++){

           if(v[i].second.weight>w){

             totalvalue+=w*v[i].first;

                w=0;

           }

           else{

             totalvalue+=v[i].second.value;

             w=w-v[i].second.weight;

           }

       }

        return totalvalue;

    }

        

};


Explanation

Inside the function:

  • A vector of pairs, where the first element is the per unit value of an item (value/weight), and the second element is the actual item, is created. This vector is named v.

  • The function cmp is a static comparison function used to sort the vector v in non-increasing order based on per unit value.


Suggested blogs:

>Find the number of pairs of elements whose sum is equal to K using C++

>How to check whether string is palindrome or not using C++

>How to determine the smallest possible size of a vertex cover using C++

>Build an Electron application from scratch

>Building Web API using ASP.NET (C#)

>Built Web API using ASP.NET (C#)


Nisha Patel

Nisha Patel

Submit
0 Answers