|
| 1 | +class Solution { |
| 2 | + public: |
| 3 | + // Function to solve the Fractional Knapsack problem |
| 4 | + double fractionalKnapsack(vector<int>& val, vector<int>& wt, int capacity) { |
| 5 | + // Create a vector to store pairs where each pair consists of the per unit value |
| 6 | + // and the corresponding (value, weight) pair for each item |
| 7 | + vector<pair<double, pair<int, int>>> v; |
| 8 | + |
| 9 | + // Step 1: Calculate the per unit value (value/weight) for each item and store it |
| 10 | + for(int i = 0; i < val.size(); i++){ |
| 11 | + double perUnitValue = 1.0 * val[i] / wt[i]; // Calculate per unit value for the item |
| 12 | + v.push_back({perUnitValue, {val[i], wt[i]}}); // Store the per unit value along with the (value, weight) pair |
| 13 | + } |
| 14 | + |
| 15 | + // Step 2: Sort the vector 'v' in decreasing order based on per unit value |
| 16 | + sort(v.begin(), v.end(), [](pair<double, pair<int, int>>& a, pair<double, pair<int, int>>& b){ |
| 17 | + return a.first > b.first; // Comparator to sort by per unit value in descending order |
| 18 | + }); |
| 19 | + |
| 20 | + // Step 3: Initialize the total value of the knapsack to 0 |
| 21 | + double totalValue = 0.0; |
| 22 | + |
| 23 | + // Step 4: Start filling the knapsack |
| 24 | + for(int i = 0; i < val.size(); i++){ |
| 25 | + int currentWeight = v[i].second.second; // Get the weight of the current item |
| 26 | + int currentValue = v[i].second.first; // Get the value of the current item |
| 27 | + double perUnitValue = v[i].first; // Get the per unit value of the current item |
| 28 | + |
| 29 | + // Step 5: Check if the current item can be fully added to the knapsack |
| 30 | + if(capacity >= currentWeight) { |
| 31 | + totalValue += currentValue; // Add the full value of the item |
| 32 | + capacity -= currentWeight; // Decrease the remaining capacity of the knapsack |
| 33 | + } else { |
| 34 | + // If the current item cannot be fully added, add the fractional part of it |
| 35 | + totalValue += capacity * perUnitValue; // Add the value for the fractional weight |
| 36 | + break; // Once the knapsack is full, break out of the loop |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + // Step 6: Return the total value of the knapsack |
| 41 | + return totalValue; |
| 42 | + } |
| 43 | +}; |
0 commit comments