Home > Backend Development > C++ > body text

Implementing the 0/1 knapsack problem in C/C++ using the branch-and-bound method

PHPz
Release: 2023-09-04 20:17:06
forward
1251 people have browsed it

Implementing the 0/1 knapsack problem in C/C++ using the branch-and-bound method

The idea is to realize the fact that greedy methods provide the best solution to the fractional knapsack problem.

To check if a specific node can provide us with a better solution, we calculate the best solution (by node) implementing a greedy approach. If the greedy method itself computes more solutions than the best solution so far, then we cannot get to a better solution through the nodes.

The complete algorithm is as follows -

  • Sort all items according to the descending order of value per unit weight ratio so that the upper limit can be calculated using the greedy method.

  • Initialize the maximum profit, for example maxProfit = 0

  • Create an empty queue Q.

  • Decision virtual nodes create trees and insert or queue them into Q. The profit and weight of the virtual node are 0.

  • Perform the following operations when Q is not empty or empty.

    • Created the project in Q. Let the extraction item be u.

    • Calculate the profit of the next level node. If the profit is higher than maxProfit, modify maxProfit.

    • Calculate the limit of the next level node. If bound is higher than maxProfit, add the next level node to Q.

    • Consider the situation where the next level node is not considered or considered as part of the solution and add the node to the queue at the level of the next level but the weight and profit are not processed Or consider the next level node.

Illustration given below -

Input
// First thing in every pair is treated as weight of item
// and second thing is treated as value of item
Item arr1[] = {{2, 40}, {3.14, 50}, {1.98, 100}, {5, 95}, {3, 30}};
Knapsack Capacity W1 = 10

Copy after login

Output

The maximum possible profit = 235
Copy after login

The above is the detailed content of Implementing the 0/1 knapsack problem in C/C++ using the branch-and-bound method. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template