给定N个项目的权重和利润,将这些项目放在容量为W的背包中。任务是打印所有可能的问题解决方案,以确保没有剩下的重量小于背包剩余容量的剩余物品。另外,计算最大利润。
例子:
Input: Profits[] = {60, 100, 120, 50}
Weights[] = {10, 20, 30, 40}, W = 40
Output:
10: 60, 20: 100,
10: 60, 30: 120,
Maximum Profit = 180
Explanation:
Maximum profit from all the possible solutions is 180
Input: Profits[] = {60, 100, 120, 50}
Weights[] = {10, 20, 30, 40}, W = 50
Output:
10: 60, 20: 100,
10: 60, 30: 120,
20: 100, 30: 120,
Maximum Profit = 220
Explanation:
Maximum profit from all the possible solutions is 220
方法:这个想法是对物品的重量和利润进行配对,然后尝试数组的所有排列并包括重量,直到它们不是重量小于背包剩余容量的物品为止。同时,在包括一个项目之后,将该解决方案的利润增加那个项目的利润。
下面是上述方法的实现:
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