📜  0/1 背包问题打印所有可能的解决方案

📅  最后修改于: 2021-09-22 10:34:22             🧑  作者: Mango

给定 N件物品的重量和利润,将这些物品放入容量为W的背包中。任务是以这样一种方式打印问题的所有可能的解决方案,即没有剩余重量小于背包剩余容量的物品。另外,计算最大利润。

例子:

方法:想法是将物品的重量和利润配对,然后尝试数组的所有排列并包括重量,直到它们没有重量小于背包剩余容量的物品。同时,在包含一个项目之后,通过该项目的利润增加该解决方案的利润。

下面是上述方法的实现:

C++
// C++ implementation to print all
// the possible solutions of the
// 0/1 Knapsack problem
  
#include 
  
using namespace std;
  
// Utility function to find the
// maximum of the two elements
int max(int a, int b) { 
    return (a > b) ? a : b; 
}
  
// Function to find the all the
// possible solutions of the 
// 0/1 knapSack problem
int knapSack(int W, vector wt, 
            vector val, int n)
{
    // Mapping weights with Profits
    map umap;
      
    set>> set_sol;
    // Making Pairs and inserting
    // into the map
    for (int i = 0; i < n; i++) {
        umap.insert({ wt[i], val[i] });
    }
  
    int result = INT_MIN;
    int remaining_weight;
    int sum = 0;
      
    // Loop to iterate over all the 
    // possible permutations of array
    do {
        sum = 0;
          
        // Initially bag will be empty
        remaining_weight = W;
        vector> possible;
          
        // Loop to fill up the bag 
        // untill there is no weight
        // such which is less than
        // remaining weight of the
        // 0-1 knapSack
        for (int i = 0; i < n; i++) {
            if (wt[i] <= remaining_weight) {
  
                remaining_weight -= wt[i];
                auto itr = umap.find(wt[i]);
                sum += (itr->second);
                possible.push_back({itr->first,
                     itr->second
                });
            }
        }
        sort(possible.begin(), possible.end());
        if (sum > result) {
            result = sum;
        }
        if (set_sol.find(possible) == 
                        set_sol.end()){
            for (auto sol: possible){
                cout << sol.first << ": "
                     << sol.second << ", ";
            }
            cout << endl;
            set_sol.insert(possible);
        }
          
    } while (
        next_permutation(wt.begin(), 
                           wt.end()));
    return result;
}
  
// Driver Code
int main()
{
    vector val{ 60, 100, 120 };
    vector wt{ 10, 20, 30 };
    int W = 50;
    int n = val.size();
    int maximum = knapSack(W, wt, val, n);
    cout << "Maximum Profit = ";
    cout << maximum;
    return 0;
}


输出:
10: 60, 20: 100, 
10: 60, 30: 120, 
20: 100, 30: 120, 
Maximum Profit = 220

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程。