![]() |
VOOZH | about |
Given N items with weights W[0..n-1], values V[0..n-1] and a knapsack with capacity C, select the items such that:
Examples:
Input: N = 4, C = 15, V[]= {10, 10, 12, 18}, W[]= {2, 4, 6, 9}
Output:
Items taken into the knapsack are
1 1 0 1
Maximum profit is 38
Explanation:
1 in the output indicates that the item is included in the knapsack while 0 indicates that the item is excluded.
Since the maximum possible cost allowed is 15, the ways to select items are:
(1 1 0 1) -> Cost = 2 + 4 + 9 = 15, Profit = 10 + 10 + 18 = 38.
(0 0 1 1) -> Cost = 6 + 9 = 15, Profit = 12 + 18 = 30
(1 1 1 0) -> Cost = 2 + 4 + 6 = 12, Profit = 32
Hence, maximum profit possible within a cost of 15 is 38.
Input: N = 4, C = 21, V[]= {18, 20, 14, 18}, W[]= {6, 3, 5, 9}
Output:
Items taken into the knapsack are
1 1 0 1
Maximum profit is 56
Explanation:
Cost = 6 + 3 + 9 = 18
Profit = 18 + 20 + 18 = 56
Approach:
In this post, the implementation of Branch and Bound method using Least cost(LC) for 0/1 Knapsack Problem is discussed.
Branch and Bound can be solved using FIFO, LIFO and LC strategies. The least cost(LC) is considered the most intelligent as it selects the next node based on a Heuristic Cost Function. It picks the one with the least cost.
As 0/1 Knapsack is about maximizing the total value, we cannot directly use the LC Branch and Bound technique to solve this. Instead, we convert this into a minimization problem by taking negative of the given values.
Follow the steps below to solve the problem:
Illustration:
π 0 1 Knapsack using Least Cost Branch and Bound
N = 4, C = 15, V[]= {10 10 12 18}, W[]= {2 4 6 9}π priority queue for 0 1 knapsack problem using Least Cost Branch and Bound
Left branch and right branch at ith level stores the maximum obtained including and excluding the ith element.
Below image shows the state of the priority queue after every step:
Below is the implementation of the above approach:
Items taken into the knapsack are : 1 1 0 1 Maximum profit is : 38