📜  分数级背包问题的C ++程序

📅  最后修改于: 2021-05-31 18:24:02             🧑  作者: Mango

先决条件:小背包问题

给定两个数组weight []profit [] N个项目的权重和利润,我们需要将这些项目放入容量为W的背包中,以在背包中获得最大的总价值。
注意:与0/1背包不同,您可以打破物品。

例子:

方法1 –不使用STL:想法是使用贪婪方法。步骤如下:

  1. 找到每个项目的比率值/重量,并根据该比率对项目进行排序。
  2. 选择比例最高的项目,然后添加它们,直到我们无法整体添加下一个项目为止。
  3. 最后,尽可能多地添加下一项。
  4. 完成上述步骤后,打印出最大利润。

下面是上述方法的实现:

C++
// C++ program to solve fractional
// Knapsack Problem
#include 
  
using namespace std;
  
// Structure for an item which stores
// weight & corresponding value of Item
struct Item {
    int value, weight;
  
    // Constructor
    Item(int value, int weight)
        : value(value), weight(weight)
    {
    }
};
  
// Comparison function to sort Item
// according to val/weight ratio
bool cmp(struct Item a, struct Item b)
{
    double r1 = (double)a.value / a.weight;
    double r2 = (double)b.value / b.weight;
    return r1 > r2;
}
  
// Main greedy function to solve problem
double fractionalKnapsack(struct Item arr[],
                          int N, int size)
{
    // Sort Item on basis of ratio
    sort(arr, arr + size, cmp);
  
    // Current weight in knapsack
    int curWeight = 0;
  
    // Result (value in Knapsack)
    double finalvalue = 0.0;
  
    // Looping through all Items
    for (int i = 0; i < size; i++) {
  
        // If adding Item won't overflow,
        // add it completely
        if (curWeight + arr[i].weight <= N) {
            curWeight += arr[i].weight;
            finalvalue += arr[i].value;
        }
  
        // If we can't add current Item,
        // add fractional part of it
        else {
            int remain = N - curWeight;
            finalvalue += arr[i].value
                          * ((double)remain
                             / arr[i].weight);
  
            break;
        }
    }
  
    // Returning final value
    return finalvalue;
}
  
// Driver Code
int main()
{
    // Weight of knapsack
    int N = 60;
  
    // Given weights and values as a pairs
    Item arr[] = { { 100, 10 },
                   { 280, 40 },
                   { 120, 20 },
                   { 120, 24 } };
  
    int size = sizeof(arr) / sizeof(arr[0]);
  
    // Function Call
    cout << "Maximum profit earned = "
         << fractionalKnapsack(arr, N, size);
    return 0;
}


C++
// C++ program to Fractional Knapsack
// Problem using STL
#include 
using namespace std;
  
// Function to find maximum profit
void maxProfit(vector profit,
               vector weight, int N)
{
  
    // Number of total weights present
    int numOfElements = profit.size();
    int i;
  
    // Multimap container to store
    // ratio and index
    multimap ratio;
  
    // Variable to store maximum profit
    double max_profit = 0;
    for (i = 0; i < numOfElements; i++) {
  
        // Insert ratio profit[i] / weight[i]
        // and corresponding index
        ratio.insert(make_pair(
            (double)profit[i] / weight[i], i));
    }
  
    // Declare a reverse iterator
    // for Multimap
    multimap::reverse_iterator it;
  
    // Traverse the map in reverse order
    for (it = ratio.rbegin(); it != ratio.rend();
         it++) {
  
        // Fraction of weight of i'th item
        // that can be kept in knapsack
        double fraction = (double)N / weight[it->second];
  
        // if remaining_weight is greater
        // than the weight of i'th item
        if (N >= 0
            && N >= weight[it->second]) {
  
            // increase max_profit by i'th
            // profit value
            max_profit += profit[it->second];
  
            // decrement knapsack to form
            // new remaining_weight
            N -= weight[it->second];
        }
  
        // remaining_weight less than
        // weight of i'th item
        else if (N < weight[it->second]) {
            max_profit += fraction
                          * profit[it->second];
            break;
        }
    }
  
    // Print the maximum profit earned
    cout << "Maximum profit earned is:"
         << max_profit;
}
  
// Driver Code
int main()
{
    // Size of list
    int size = 4;
  
    // Given profit and weight
    vector profit(size), weight(size);
  
    // Profit of items
    profit[0] = 100, profit[1] = 280,
    profit[2] = 120, profit[3] = 120;
  
    // Weight of items
    weight[0] = 10, weight[1] = 40,
    weight[2] = 20, weight[3] = 24;
  
    // Capacity of knapsack
    int N = 60;
  
    // Function Call
    maxProfit(profit, weight, N);
}


输出:
Maximum profit earned = 440

时间复杂度: O(N * log 2 N)
辅助空间: O(1)

方法2 –使用STL:

  1. 为每个元素创建一个地图,其中profit [i] / weight [i]为第一个元素,i为第二个元素。
  2. 定义变量max_profit = 0
  3. 以相反的方式遍历地图:
    • 创建一个名为fraction的变量,其值等于remaining_weight / weight [i]。
    • 如果剩余权重大于或等于零并且其值大于权重[i],则将当前利润添加到max_profit,并按权重[i]减少剩余权重。
    • 否则,如果剩余权重小于weight [i],则将分数* Profit [i]添加到max_profit并中断。
  4. 打印max_profit

下面是上述方法的实现:

C++

// C++ program to Fractional Knapsack
// Problem using STL
#include 
using namespace std;
  
// Function to find maximum profit
void maxProfit(vector profit,
               vector weight, int N)
{
  
    // Number of total weights present
    int numOfElements = profit.size();
    int i;
  
    // Multimap container to store
    // ratio and index
    multimap ratio;
  
    // Variable to store maximum profit
    double max_profit = 0;
    for (i = 0; i < numOfElements; i++) {
  
        // Insert ratio profit[i] / weight[i]
        // and corresponding index
        ratio.insert(make_pair(
            (double)profit[i] / weight[i], i));
    }
  
    // Declare a reverse iterator
    // for Multimap
    multimap::reverse_iterator it;
  
    // Traverse the map in reverse order
    for (it = ratio.rbegin(); it != ratio.rend();
         it++) {
  
        // Fraction of weight of i'th item
        // that can be kept in knapsack
        double fraction = (double)N / weight[it->second];
  
        // if remaining_weight is greater
        // than the weight of i'th item
        if (N >= 0
            && N >= weight[it->second]) {
  
            // increase max_profit by i'th
            // profit value
            max_profit += profit[it->second];
  
            // decrement knapsack to form
            // new remaining_weight
            N -= weight[it->second];
        }
  
        // remaining_weight less than
        // weight of i'th item
        else if (N < weight[it->second]) {
            max_profit += fraction
                          * profit[it->second];
            break;
        }
    }
  
    // Print the maximum profit earned
    cout << "Maximum profit earned is:"
         << max_profit;
}
  
// Driver Code
int main()
{
    // Size of list
    int size = 4;
  
    // Given profit and weight
    vector profit(size), weight(size);
  
    // Profit of items
    profit[0] = 100, profit[1] = 280,
    profit[2] = 120, profit[3] = 120;
  
    // Weight of items
    weight[0] = 10, weight[1] = 40,
    weight[2] = 20, weight[3] = 24;
  
    // Capacity of knapsack
    int N = 60;
  
    // Function Call
    maxProfit(profit, weight, N);
}
输出:
Maximum profit earned is:440

时间复杂度: O(N)
辅助空间: O(N)

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。