The Wayback Machine - https://web.archive.org/web/20240917102232/https://www.geeksforgeeks.org/0-1-knapsack-using-least-count-branch-and-bound/
Open In App

0/1 Knapsack using Least Cost Branch and Bound

Last Updated : 09 Jan, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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: 
 

  1. The sum of weights taken into the knapsack is less than or equal to C.
  2. The sum of values of the items in the knapsack is maximum among all the possible combinations.

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: 
 

  1. Sort the items based on their value/weight(V/W) ratio.
  2. Insert a dummy node into the priority queue.
  3. Repeat the following steps until the priority queue is empty:
    • Extract the peek element from the priority queue and assign it to the current node.
    • If the upper bound of the current node is less than minLB, the minimum lower bound of all the nodes explored, then there is no point of exploration. So, continue with the next element. The reason for not considering the nodes whose upper bound is greater than minLB is that, the upper bound stores the best value that might be achieved. If the best value itself is not optimal than minLB, then exploring that path is of no use. 
       
    • Update the path array.
    • If the current node’s level is N, then check whether the lower bound of the current node is less than finalLB, minimum lower bound of all the paths that reached the final level. If it is true, update the finalPath and finalLB. Otherwise, continue with the next element.
    • Calculate the lower and upper bounds of the right child of the current node.
    • If the current item can be inserted into the knapsack, then calculate the lower and upper bound of the left child of the current node.
    • Update the minLB and insert the children if their upper bound is less than minLB.

 

Illustration: 
N = 4, C = 15, V[]= {10 10 12 18}, W[]= {2 4 6 9} 
 

0 1 Knapsack 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: 
 

priority queue for 0 1 knapsack problem using Least Cost Branch and Bound

 

Below is the implementation of the above approach:
 

C++




#include <iostream>
#include <algorithm>
#include <queue>
 
using namespace std;
 
// Class to represent an item
class Item {
public:
    float weight;
    int value;
    int idx;
 
    // Constructor to initialize an item
    Item(int value, float weight, int idx) : value(value), weight(weight), idx(idx) {}
};
 
// Class to represent a node in the branch and bound algorithm
class Node {
public:
    float ub;    // Upper bound
    float lb;    // Lower bound
    int level;   // Level in the decision tree
    bool flag;   // Flag to indicate if the item is selected or not
    float tv;    // Total value of selected items
    float tw;    // Total weight of selected items
 
    // Default constructor
    Node() {}
 
    // Copy constructor
    Node(const Node& cpy) : tv(cpy.tv), tw(cpy.tw), ub(cpy.ub), lb(cpy.lb), level(cpy.level), flag(cpy.flag) {}
};
 
// Comparator to sort nodes based on lower bound
class sortByC {
public:
    bool operator()(const Node& a, const Node& b) const {
        return a.lb > b.lb;
    }
};
 
// Comparator to sort items based on value/weight ratio
class sortByRatio {
public:
    bool operator()(const Item& a, const Item& b) const {
        return static_cast<float>(a.value) / a.weight > static_cast<float>(b.value) / b.weight;
    }
};
 
// Function to assign values to a node
void assign(Node& a, float ub, float lb, int level, bool flag, float tv, float tw) {
    a.ub = ub;
    a.lb = lb;
    a.level = level;
    a.flag = flag;
    a.tv = tv;
    a.tw = tw;
}
 
// Function to calculate the upper bound (best case) considering fractional knapsack
float upperBound(float tv, float tw, int idx, Item arr[], int size, float capacity) {
    float value = tv;
    float weight = tw;
 
    // Iterate over the remaining items and add them to the knapsack if possible
    for (int i = idx; i < size; i++) {
        if (weight + arr[i].weight <= capacity) {
            weight += arr[i].weight;
            value -= arr[i].value;
        } else {
            // If the remaining capacity is not enough for the entire item, add a fraction of it
            value -= static_cast<float>(capacity - weight) / arr[i].weight * arr[i].value;
            break;
        }
    }
    return value;
}
 
// Function to calculate the lower bound (worst case) without considering fractional part of items
float lowerBound(float tv, float tw, int idx, Item arr[], int size, float capacity) {
    float value = tv;
    float weight = tw;
 
    // Iterate over the remaining items and add them to the knapsack if possible
    for (int i = idx; i < size; i++) {
        if (weight + arr[i].weight <= capacity) {
            weight += arr[i].weight;
            value -= arr[i].value;
        } else {
            break;
        }
    }
    return value;
}
 
// Function to solve the 0/1 knapsack problem using branch and bound
void solve(Item arr[], int size, float capacity) {
    // Sort the items based on the value/weight ratio
    sort(arr, arr + size, sortByRatio());
 
    // Initialize nodes
    Node current, left, right;
    current.tv = current.tw = current.ub = current.lb = 0;
    current.level = 0;
    current.flag = false;
 
    float minLB = 0, finalLB = numeric_limits<float>::max();
    current.tv = current.tw = current.ub = current.lb = 0;
    current.level = 0;
    current.flag = false;
 
    // Priority queue to store nodes based on lower bounds
    priority_queue<Node, vector<Node>, sortByC> pq;
    pq.push(current);
 
    // Arrays to store the current and final selection of items
    bool currPath[size];
    bool finalPath[size];
 
    // Explore nodes in the priority queue
    while (!pq.empty()) {
        current = pq.top();
        pq.pop();
 
        // Prune if the upper bound is greater than the minimum lower bound
        if (current.ub > minLB || current.ub >= finalLB) {
            continue;
        }
 
        // Store the selection if it reaches the final level
        if (current.level != 0)
            currPath[current.level - 1] = current.flag;
 
        // Check if it's the last level and update the final selection if the lower bound is better
        if (current.level == size) {
            if (current.lb < finalLB) {
                for (int i = 0; i < size; i++)
                    finalPath[arr[i].idx] = currPath[i];
                finalLB = current.lb;
            }
            continue;
        }
 
        int level = current.level;
 
        // Explore the right node (exclude current item)
        assign(right, upperBound(current.tv, current.tw, level + 1, arr, size, capacity),
               lowerBound(current.tv, current.tw, level + 1, arr, size, capacity),
               level + 1, false, current.tv, current.tw);
 
        // Explore the left node (include current item)
        if (current.tw + arr[current.level].weight <= capacity) {
            left.ub = upperBound(current.tv - arr[level].value, current.tw + arr[level].weight, level + 1, arr, size, capacity);
            left.lb = lowerBound(current.tv - arr[level].value, current.tw + arr[level].weight, level + 1, arr, size, capacity);
            assign(left, left.ub, left.lb, level + 1, true, current.tv - arr[level].value, current.tw + arr[level].weight);
        } else {
            // If the left node cannot be inserted, stop it from getting added to the priority queue
            left.ub = left.lb = 1;
        }
 
        // Update minLB
        minLB = min(minLB, left.lb);
        minLB = min(minLB, right.lb);
 
        // Add nodes to the priority queue if their upper bounds are less than minLB
        if (minLB >= left.ub)
            pq.push(left);
        if (minLB >= right.ub)
            pq.push(right);
    }
 
    // Print the final result
    cout << "Items taken into the knapsack are\n";
    for (int i = 0; i < size; i++) {
        if (finalPath[i])
            cout << "1 ";
        else
            cout << "0 ";
    }
    cout << "\nMaximum profit is " << -finalLB << endl;
}
 
// Main function
int main() {
    int size = 4;
    float capacity = 15;
 
    // Create an array of items
    Item arr[] = {Item(10, 2, 0), Item(10, 4, 1), Item(12, 6, 2), Item(18, 9, 3)};
 
    // Call the solve function to solve the knapsack problem
    solve(arr, size, capacity);
 
    return 0;
}
// This code is contributed by arindam369


Java




// Java Program to implement
// 0/1 knapsack using LC
// Branch and Bound
 
import java.util.*;
class Item {
 
    // Stores the weight
    // of items
    float weight;
 
    // Stores the values
    // of items
    int value;
 
    // Stores the index
    // of items
    int idx;
    public Item() {}
    public Item(int value, float weight,
                int idx)
    {
        this.value = value;
        this.weight = weight;
        this.idx = idx;
    }
}
 
class Node {
    // Upper Bound: Best case
    // (Fractional Knapsack)
    float ub;
 
    // Lower Bound: Worst case
    // (0/1)
    float lb;
 
    // Level of the node in
    // the decision tree
    int level;
 
    // Stores if the current
    // item is selected or not
    boolean flag;
 
    // Total Value: Stores the
    // sum of the values of the
    // items included
    float tv;
 
    // Total Weight: Stores the sum of
    // the weights of included items
    float tw;
    public Node() {}
    public Node(Node cpy)
    {
        this.tv = cpy.tv;
        this.tw = cpy.tw;
        this.ub = cpy.ub;
        this.lb = cpy.lb;
        this.level = cpy.level;
        this.flag = cpy.flag;
    }
}
 
// Comparator to sort based on lower bound
class sortByC implements Comparator<Node> {
    public int compare(Node a, Node b)
    {
        boolean temp = a.lb > b.lb;
        return temp ? 1 : -1;
    }
}
 
class sortByRatio implements Comparator<Item> {
    public int compare(Item a, Item b)
    {
        boolean temp = (float)a.value
                           / a.weight
                       > (float)b.value
                             / b.weight;
        return temp ? -1 : 1;
    }
}
 
class knapsack {
 
    private static int size;
    private static float capacity;
 
    // Function to calculate upper bound
    // (includes fractional part of the items)
    static float upperBound(float tv, float tw,
                            int idx, Item arr[])
    {
        float value = tv;
        float weight = tw;
        for (int i = idx; i < size; i++) {
            if (weight + arr[i].weight
                <= capacity) {
                weight += arr[i].weight;
                value -= arr[i].value;
            }
            else {
                value -= (float)(capacity
                                 - weight)
                         / arr[i].weight
                         * arr[i].value;
                break;
            }
        }
        return value;
    }
 
    // Calculate lower bound (doesn't
    // include fractional part of items)
    static float lowerBound(float tv, float tw,
                            int idx, Item arr[])
    {
        float value = tv;
        float weight = tw;
        for (int i = idx; i < size; i++) {
            if (weight + arr[i].weight
                <= capacity) {
                weight += arr[i].weight;
                value -= arr[i].value;
            }
            else {
                break;
            }
        }
        return value;
    }
 
    static void assign(Node a, float ub, float lb,
                       int level, boolean flag,
                       float tv, float tw)
    {
        a.ub = ub;
        a.lb = lb;
        a.level = level;
        a.flag = flag;
        a.tv = tv;
        a.tw = tw;
    }
 
    public static void solve(Item arr[])
    {
        // Sort the items based on the
        // profit/weight ratio
        Arrays.sort(arr, new sortByRatio());
 
        Node current, left, right;
        current = new Node();
        left = new Node();
        right = new Node();
 
        // min_lb -> Minimum lower bound
        // of all the nodes explored
 
        // final_lb -> Minimum lower bound
        // of all the paths that reached
        // the final level
        float minLB = 0, finalLB
                         = Integer.MAX_VALUE;
        current.tv = current.tw = current.ub
            = current.lb = 0;
        current.level = 0;
        current.flag = false;
 
        // Priority queue to store elements
        // based on lower bounds
        PriorityQueue<Node> pq
            = new PriorityQueue<Node>(
                new sortByC());
 
        // Insert a dummy node
        pq.add(current);
 
        // curr_path -> Boolean array to store
        // at every index if the element is
        // included or not
 
        // final_path -> Boolean array to store
        // the result of selection array when
        // it reached the last level
        boolean currPath[] = new boolean[size];
        boolean finalPath[] = new boolean[size];
 
        while (!pq.isEmpty()) {
            current = pq.poll();
            if (current.ub > minLB
                || current.ub >= finalLB) {
                // if the current node's best case
                // value is not optimal than minLB,
                // then there is no reason to
                // explore that node. Including
                // finalLB eliminates all those
                // paths whose best values is equal
                // to the finalLB
                continue;
            }
 
            if (current.level != 0)
                currPath[current.level - 1]
                    = current.flag;
 
            if (current.level == size) {
                if (current.lb < finalLB) {
                    // Reached last level
                    for (int i = 0; i < size; i++)
                        finalPath[arr[i].idx]
                            = currPath[i];
                    finalLB = current.lb;
                }
                continue;
            }
 
            int level = current.level;
 
            // right node -> Excludes current item
            // Hence, cp, cw will obtain the value
            // of that of parent
            assign(right, upperBound(current.tv,
                                     current.tw,
                                     level + 1, arr),
                   lowerBound(current.tv, current.tw,
                              level + 1, arr),
                   level + 1, false,
                   current.tv, current.tw);
 
            if (current.tw + arr[current.level].weight
                <= capacity) {
 
                // left node -> includes current item
                // c and lb should be calculated
                // including the current item.
                left.ub = upperBound(
                    current.tv
                        - arr[level].value,
                    current.tw
                        + arr[level].weight,
                    level + 1, arr);
                left.lb = lowerBound(
                    current.tv
                        - arr[level].value,
                    current.tw
                        + arr[level].weight,
                    level + 1,
                    arr);
                assign(left, left.ub, left.lb,
                       level + 1, true,
                       current.tv - arr[level].value,
                       current.tw
                           + arr[level].weight);
            }
 
            // If the left node cannot
            // be inserted
            else {
 
                // Stop the left node from
                // getting added to the
                // priority queue
                left.ub = left.lb = 1;
            }
 
            // Update minLB
            minLB = Math.min(minLB, left.lb);
            minLB = Math.min(minLB, right.lb);
 
            if (minLB >= left.ub)
                pq.add(new Node(left));
            if (minLB >= right.ub)
                pq.add(new Node(right));
        }
        System.out.println("Items taken"
                           + "into the knapsack are");
        for (int i = 0; i < size; i++) {
            if (finalPath[i])
                System.out.print("1 ");
            else
                System.out.print("0 ");
        }
        System.out.println("\nMaximum profit"
                           + " is " + (-finalLB));
    }
 
    // Driver code
    public static void main(String args[])
    {
        size = 4;
        capacity = 15;
 
        Item arr[] = new Item[size];
        arr[0] = new Item(10, 2, 0);
        arr[1] = new Item(10, 4, 1);
        arr[2] = new Item(12, 6, 2);
        arr[3] = new Item(18, 9, 3);
 
        solve(arr);
    }
}


Python3




class Item:
    def __init__(self, value, weight, idx):
        self.value = value
        self.weight = weight
        self.idx = idx
 
class Node:
    def __init__(self):
        self.ub = 0  # Upper bound
        self.lb = 0  # Lower bound
        self.level = 0  # Level in the decision tree
        self.flag = False  # Flag to indicate if the item is selected or not
        self.tv = 0  # Total value of selected items
        self.tw = 0  # Total weight of selected items
 
def assign(a, ub, lb, level, flag, tv, tw):
    # Helper function to assign values to a Node object
    a.ub = ub
    a.lb = lb
    a.level = level
    a.flag = flag
    a.tv = tv
    a.tw = tw
 
def upper_bound(tv, tw, idx, arr, capacity):
    # Calculate the upper bound of the current node
    value, weight = tv, tw
    for i in range(idx, len(arr)):
        if weight + arr[i].weight <= capacity:
            weight += arr[i].weight
            value -= arr[i].value
        else:
            value -= ((capacity - weight) / arr[i].weight) * arr[i].value
            break
    return value
 
def lower_bound(tv, tw, idx, arr, capacity):
    # Calculate the lower bound of the current node
    value, weight = tv, tw
    for i in range(idx, len(arr)):
        if weight + arr[i].weight <= capacity:
            weight += arr[i].weight
            value -= arr[i].value
        else:
            break
    return value
 
def solve(arr, capacity):
    # Main function to solve the 0/1 Knapsack problem using Branch and Bound
 
    # Sort items by value-to-weight ratio in descending order
    arr.sort(key=lambda x: x.value / x.weight, reverse=True)
 
    # Initialize the root node
    current = Node()
    current.tv = current.tw = current.ub = current.lb = 0
    current.level = 0
    current.flag = False
 
    # Initialize variables to track the best solution
    min_lb = 0
    final_lb = float('inf')
    current.tv = current.tw = current.ub = current.lb = 0
    current.level = 0
    current.flag = False
 
    # Lists to track the current and final selected items
    curr_path = [False] * len(arr)
    final_path = [False] * len(arr)
 
    # Priority queue for node exploration
    pq = []
    pq.append(current)
 
    while pq:
        current = pq.pop(0)
 
        # Prune the node if its upper bound is greater than the current minimum lower bound
        if current.ub > min_lb or current.ub >= final_lb:
            continue
 
        if current.level != 0:
            curr_path[current.level - 1] = current.flag
 
        # Check if the current node is a leaf node
        if current.level == len(arr):
            # Update the final solution if the current lower bound is better
            if current.lb < final_lb:
                for i in range(len(arr)):
                    final_path[arr[i].idx] = curr_path[i]
                final_lb = current.lb
            continue
 
        level = current.level
 
        # Explore right child (item is not included in the knapsack)
        right = Node()
        right.ub = upper_bound(current.tv, current.tw, level + 1, arr, capacity)
        right.lb = lower_bound(current.tv, current.tw, level + 1, arr, capacity)
        assign(right, right.ub, right.lb, level + 1, False, current.tv, current.tw)
 
        # Explore left child (item is included in the knapsack)
        left = Node()
        if current.tw + arr[current.level].weight <= capacity:
            left.ub = upper_bound(
                current.tv - arr[level].value,
                current.tw + arr[level].weight,
                level + 1,
                arr,
                capacity
            )
            left.lb = lower_bound(
                current.tv - arr[level].value,
                current.tw + arr[level].weight,
                level + 1,
                arr,
                capacity
            )
            assign(
                left,
                left.ub,
                left.lb,
                level + 1,
                True,
                current.tv - arr[level].value,
                current.tw + arr[level].weight
            )
        else:
            # If adding the current item exceeds the capacity, set bounds to 1
            left.ub = 1
            left.lb = 1
 
        min_lb = min(min_lb, left.lb, right.lb)
 
        # Add valid children to the priority queue for further exploration
        if min_lb >= left.ub:
            pq.append(left)
        if min_lb >= right.ub:
            pq.append(right)
 
    # Print the selected items and maximum profit
    print("Items taken into the knapsack are")
    max_profit = -final_lb
    for i in range(len(arr)):
        if final_path[i]:
            print("1")
        else:
            print("0")
    print("Maximum profit is", max_profit)
 
# Main function
def main():
    # Example usage
    capacity = 15
    arr = [
        Item(10, 2, 0),
        Item(10, 4, 1),
        Item(12, 6, 2),
        Item(18, 9, 3),
    ]
 
    solve(arr, capacity)
 
if __name__ == "__main__":
    main()


C#




using System;
using System.Collections.Generic;
 
// Class to represent an item
class Item
{
    public float Weight { get; set; }
    public int Value { get; set; }
    public int Index { get; set; }
 
    // Constructor to initialize an item
    public Item(int value, float weight, int index)
    {
        Value = value;
        Weight = weight;
        Index = index;
    }
}
 
// Class to represent a node in the branch and bound algorithm
class Node
{
    public float UpperBound { get; set; }
    public float LowerBound { get; set; }
    public int Level { get; set; }
    public bool Flag { get; set; }
    public float TotalValue { get; set; }
    public float TotalWeight { get; set; }
 
    // Default constructor
    public Node() { }
 
    // Copy constructor
    public Node(Node copy)
    {
        TotalValue = copy.TotalValue;
        TotalWeight = copy.TotalWeight;
        UpperBound = copy.UpperBound;
        LowerBound = copy.LowerBound;
        Level = copy.Level;
        Flag = copy.Flag;
    }
}
 
// Comparator to sort nodes based on lower bound
class SortByC : IComparer<Node>
{
    public int Compare(Node a, Node b)
    {
        return a.LowerBound.CompareTo(b.LowerBound);
    }
}
 
// Comparator to sort items based on value/weight ratio
class SortByRatio : IComparer<Item>
{
    public int Compare(Item a, Item b)
    {
        return ((float)a.Value / a.Weight).CompareTo((float)b.Value / b.Weight);
    }
}
 
class Program
{
    // Function to assign values to a node
    static void Assign(Node a, float ub, float lb, int level, bool flag, float tv, float tw)
    {
        a.UpperBound = ub;
        a.LowerBound = lb;
        a.Level = level;
        a.Flag = flag;
        a.TotalValue = tv;
        a.TotalWeight = tw;
    }
 
    // Function to calculate the upper bound (best case) considering fractional knapsack
    static float UpperBound(float tv, float tw, int idx, Item[] arr, int size, float capacity)
    {
        float value = tv;
        float weight = tw;
 
        // Iterate over the remaining items and add them to the knapsack if possible
        for (int i = idx; i < size; i++)
        {
            if (weight + arr[i].Weight <= capacity)
            {
                weight += arr[i].Weight;
                value -= arr[i].Value;
            }
            else
            {
                // If the remaining capacity is not enough for the entire item, add a fraction of it
                value -= ((capacity - weight) / arr[i].Weight) * arr[i].Value;
                break;
            }
        }
        return value;
    }
 
    // Function to calculate the lower bound (worst case) without considering fractional part of items
    static float LowerBound(float tv, float tw, int idx, Item[] arr, int size, float capacity)
    {
        float value = tv;
        float weight = tw;
 
        // Iterate over the remaining items and add them to the knapsack if possible
        for (int i = idx; i < size; i++)
        {
            if (weight + arr[i].Weight <= capacity)
            {
                weight += arr[i].Weight;
                value -= arr[i].Value;
            }
            else
            {
                break;
            }
        }
        return value;
    }
 
    // Function to solve the 0/1 knapsack problem using branch and bound
    static void Solve(Item[] arr, int size, float capacity)
    {
        // Sort the items based on the value/weight ratio
        Array.Sort(arr, new SortByRatio());
 
        // Initialize nodes
        Node current = new Node();
        Node left = new Node();
        Node right = new Node();
        current.TotalValue = current.TotalWeight = current.UpperBound = current.LowerBound = 0;
        current.Level = 0;
        current.Flag = false;
 
        float minLB = 0, finalLB = float.MaxValue;
        current.TotalValue = current.TotalWeight = current.UpperBound = current.LowerBound = 0;
        current.Level = 0;
        current.Flag = false;
 
        // Priority queue to store nodes based on lower bounds
        PriorityQueue<Node> pq = new PriorityQueue<Node>(new SortByC());
        pq.Enqueue(current);
 
        // Arrays to store the current and final selection of items
        bool[] currPath = new bool[size];
        bool[] finalPath = new bool[size];
 
        // Explore nodes in the priority queue
        while (pq.Count > 0)
        {
            current = pq.Dequeue();
 
            // Prune if the upper bound is greater than the minimum lower bound
            if (current.UpperBound > minLB || current.UpperBound >= finalLB)
            {
                continue;
            }
 
            // Store the selection if it reaches the final level
            if (current.Level != 0)
                currPath[current.Level - 1] = current.Flag;
 
            // Check if it's the last level and update the final selection if the lower bound is better
            if (current.Level == size)
            {
                if (current.LowerBound < finalLB)
                {
                    for (int i = 0; i < size; i++)
                        finalPath[arr[i].Index] = currPath[i];
                    finalLB = current.LowerBound;
                }
                continue;
            }
 
            int level = current.Level;
 
            // Explore the right node (exclude current item)
            Assign(right, UpperBound(current.TotalValue, current.TotalWeight, level + 1, arr, size, capacity),
                   LowerBound(current.TotalValue, current.TotalWeight, level + 1, arr, size, capacity),
                   level + 1, false, current.TotalValue, current.TotalWeight);
 
            // Explore the left node (include current item)
            if (current.TotalWeight + arr[current.Level].Weight <= capacity)
            {
                left.UpperBound = UpperBound(current.TotalValue - arr[level].Value, current.TotalWeight + arr[level].Weight, level + 1, arr, size, capacity);
                left.LowerBound = LowerBound(current.TotalValue - arr[level].Value, current.TotalWeight + arr[level].Weight, level + 1, arr, size, capacity);
                Assign(left, left.UpperBound, left.LowerBound, level + 1, true, current.TotalValue - arr[level].Value, current.TotalWeight + arr[level].Weight);
            }
            else
            {
                // If the left node cannot be inserted, stop it from getting added to the priority queue
                left.UpperBound = left.LowerBound = 1;
            }
 
            // Update minLB
            minLB = Math.Min(minLB, left.LowerBound);
            minLB = Math.Min(minLB, right.LowerBound);
 
            // Add nodes to the priority queue if their upper bounds are less than minLB
            if (minLB >= left.UpperBound)
                pq.Enqueue(left);
            if (minLB >= right.UpperBound)
                pq.Enqueue(right);
        }
 
        // Print the final result
        Console.WriteLine("Items taken into the knapsack are");
        for (int i = 0; i < size; i++)
        {
            if (finalPath[i])
                Console.Write("1 ");
            else
                Console.Write("0 ");
        }
        Console.WriteLine($"\nMaximum profit is {-finalLB}");
    }
 
    // Main function
    static void Main()
    {
        int size = 4;
        float capacity = 15;
 
        // Create an array of items
        Item[] arr = { new Item(10, 2, 0), new Item(10, 4, 1), new Item(12, 6, 2), new Item(18, 9, 3) };
 
        // Call the solve function to solve the knapsack problem
        Solve(arr, size, capacity);
    }
}
 
// Priority Queue implementation for C#
public class PriorityQueue<T>
{
    private List<T> list;
    private IComparer<T> comparer;
 
    public PriorityQueue(IComparer<T> comparer)
    {
        this.list = new List<T>();
        this.comparer = comparer;
    }
 
    public int Count
    {
        get { return list.Count; }
    }
 
    public void Enqueue(T item)
    {
        list.Add(item);
        int i = list.Count - 1;
 
        while (i > 0)
        {
            int parent = (i - 1) / 2;
 
            if (comparer.Compare(list[i], list[parent]) >= 0)
                break;
 
            Swap(i, parent);
            i = parent;
        }
    }
 
    public T Dequeue()
    {
        int count = list.Count;
 
        if (count == 0)
            throw new InvalidOperationException("Queue is empty");
 
        T root = list[0];
 
        if (count == 1)
        {
            list.RemoveAt(0);
        }
        else
        {
            list[0] = list[count - 1];
            list.RemoveAt(count - 1);
            Heapify(0);
        }
 
        return root;
    }
 
    private void Heapify(int i)
    {
        int leftChild, rightChild, smallestChild;
 
        while (true)
        {
            leftChild = 2 * i + 1;
            rightChild = 2 * i + 2;
            smallestChild = i;
 
            if (leftChild < list.Count && comparer.Compare(list[leftChild], list[smallestChild]) < 0)
                smallestChild = leftChild;
 
            if (rightChild < list.Count && comparer.Compare(list[rightChild], list[smallestChild]) < 0)
                smallestChild = rightChild;
 
            if (smallestChild == i)
                break;
 
            Swap(i, smallestChild);
            i = smallestChild;
        }
    }
 
    private void Swap(int i, int j)
    {
        T temp = list[i];
        list[i] = list[j];
        list[j] = temp;
    }
}


Javascript




class Item {
  constructor(value, weight, idx) {
    this.value = value;
    this.weight = weight;
    this.idx = idx;
  }
}
 
class Node {
  constructor() {
    this.ub = 0; // Upper bound
    this.lb = 0; // Lower bound
    this.level = 0; // Level in the decision tree
    this.flag = false; // Flag to indicate if the item is selected or not
    this.tv = 0; // Total value of selected items
    this.tw = 0; // Total weight of selected items
  }
}
 
function assign(a, ub, lb, level, flag, tv, tw) {
  a.ub = ub;
  a.lb = lb;
  a.level = level;
  a.flag = flag;
  a.tv = tv;
  a.tw = tw;
}
 
function upperBound(tv, tw, idx, arr, capacity) {
  let value = tv;
  let weight = tw;
 
  for (let i = idx; i < arr.length; i++) {
    if (weight + arr[i].weight <= capacity) {
      weight += arr[i].weight;
      value -= arr[i].value;
    } else {
      value -= ((capacity - weight) / arr[i].weight) * arr[i].value;
      break;
    }
  }
  return value;
}
 
function lowerBound(tv, tw, idx, arr, capacity) {
  let value = tv;
  let weight = tw;
 
  for (let i = idx; i < arr.length; i++) {
    if (weight + arr[i].weight <= capacity) {
      weight += arr[i].weight;
      value -= arr[i].value;
    } else {
      break;
    }
  }
  return value;
}
 
function solve(arr, capacity) {
  arr.sort((a, b) => b.value / b.weight - a.value / a.weight);
 
  let current = new Node();
  current.tv = current.tw = current.ub = current.lb = 0;
  current.level = 0;
  current.flag = false;
 
  let minLB = 0,
    finalLB = Number.MAX_SAFE_INTEGER;
  current.tv = current.tw = current.ub = current.lb = 0;
  current.level = 0;
  current.flag = false;
 
  let currPath = Array(arr.length).fill(false);
  let finalPath = Array(arr.length).fill(false);
 
  let pq = [];
  pq.push(current);
 
  while (pq.length > 0) {
    current = pq.shift();
 
    if (current.ub > minLB || current.ub >= finalLB) {
      continue;
    }
 
    if (current.level !== 0) currPath[current.level - 1] = current.flag;
 
    if (current.level === arr.length) {
      if (current.lb < finalLB) {
        for (let i = 0; i < arr.length; i++)
          finalPath[arr[i].idx] = currPath[i];
        finalLB = current.lb;
      }
      continue;
    }
 
    let level = current.level;
 
    let right = new Node();
    right.ub = upperBound(
      current.tv,
      current.tw,
      level + 1,
      arr,
      capacity
    );
    right.lb = lowerBound(
      current.tv,
      current.tw,
      level + 1,
      arr,
      capacity
    );
    assign(right, right.ub, right.lb, level + 1, false, current.tv, current.tw);
 
    let left = new Node();
    if (current.tw + arr[current.level].weight <= capacity) {
      left.ub = upperBound(
        current.tv - arr[level].value,
        current.tw + arr[level].weight,
        level + 1,
        arr,
        capacity
      );
      left.lb = lowerBound(
        current.tv - arr[level].value,
        current.tw + arr[level].weight,
        level + 1,
        arr,
        capacity
      );
      assign(
        left,
        left.ub,
        left.lb,
        level + 1,
        true,
        current.tv - arr[level].value,
        current.tw + arr[level].weight
      );
    } else {
      left.ub = 1;
      left.lb = 1;
    }
 
    minLB = Math.min(minLB, left.lb);
    minLB = Math.min(minLB, right.lb);
 
    if (minLB >= left.ub) pq.push(left);
    if (minLB >= right.ub) pq.push(right);
  }
 
  console.log("Items taken into the knapsack are");
  let maxProfit = -finalLB;
  for (let i = 0; i < arr.length; i++) {
    if (finalPath[i]) console.log("1");
    else console.log("0");
  }
  console.log("Maximum profit is " + maxProfit);
}
 
// Main function
function main() {
  const capacity = 15;
  const arr = [
    new Item(10, 2, 0),
    new Item(10, 4, 1),
    new Item(12, 6, 2),
    new Item(18, 9, 3),
  ];
 
  solve(arr, capacity);
}
 
main();


Output

Items taken into the knapsack are : 
1 1 0 1 
Maximum profit is : 38













Previous Article
Next Article

Similar Reads

Implementation of 0/1 Knapsack using Branch and Bound
Given two arrays v[] and w[] that represent values and weights associated with n items respectively. Find out the maximum value subset(Maximum Profit) of v[] such that the sum of the weights of this subset is smaller than or equal to Knapsack capacity Cap(W). Note: The constraint here is we can either put an item completely into the bag or cannot p
15+ min read
0/1 Knapsack using Branch and Bound
Given two arrays v[] and w[] that represent values and weights associated with n items respectively. Find out the maximum value subset(Maximum Profit) of v[] such that the sum of the weights of this subset is smaller than or equal to Knapsack capacity W. Note: The constraint here is we can either put an item completely into the bag or cannot put it
15+ min read
Generate Binary Strings of length N using Branch and Bound
The task is to generate a binary string of length N using branch and bound technique Examples: Input: N = 3 Output: 000 001 010 011 100 101 110 111 Explanation: Numbers with 3 binary digits are 0, 1, 2, 3, 4, 5, 6, 7 Input: N = 2 Output: 00 01 10 11 Approach: Generate Combinations using Branch and Bound : It starts with an empty solution vector.Whi
6 min read
Traveling Salesman Problem using Branch And Bound
Given a set of cities and distance between every pair of cities, the problem is to find the shortest possible tour that visits every city exactly once and returns to the starting point. For example, consider the graph shown in figure on right side. A TSP tour in the graph is 0-1-3-2-0. The cost of the tour is 10+25+30+15 which is 80.We have discuss
15+ min read
N Queen Problem using Branch And Bound
The N queens puzzle is the problem of placing N chess queens on an N×N chessboard so that no two queens threaten each other. Thus, a solution requires that no two queens share the same row, column, or diagonal. The backtracking Algorithm for N-Queen is already discussed here. In a backtracking solution, we backtrack when we hit a dead end. In Branc
15+ min read
Job Assignment Problem using Branch And Bound
Let there be N workers and N jobs. Any worker can be assigned to perform any job, incurring some cost that may vary depending on the work-job assignment. It is required to perform all jobs by assigning exactly one worker to each job and exactly one job to each agent in such a way that the total cost of the assignment is minimized. Let us explore al
15+ min read
Difference between 0/1 Knapsack problem and Fractional Knapsack problem
What is Knapsack Problem?Suppose you have been given a knapsack or bag with a limited weight capacity, and each item has some weight and value. The problem here is that "Which item is to be placed in the knapsack such that the weight limit does not exceed and the total value of the items is as large as possible?". Consider the real-life example. Su
13 min read
Difference Between Greedy Knapsack and 0/1 Knapsack Algorithms
The 0/1 Knapsack algorithm is a dynamic programming approach where items are either completely included or not at all. It considers all combinations to find the maximum total value. On the other hand, the Greedy Knapsack algorithm, also known as the Fractional Knapsack, allows for items to be broken into fractions, selecting items with the highest
9 min read
Applications, Advantages and Disadvantages of Branch and Bound Algorithm
Branch and bound algorithm is a method used in computer science to find the best solution to optimization problems. It systematically explores all potential solutions by breaking the problem down into smaller parts and then uses limits or rules to prevent certain parts from being considered. Applications of Branch and Bound:Combinatorial Optimizati
2 min read
Difference between Backtracking and Branch-N-Bound technique
Algorithms are the methodical sequence of steps which are defined to solve complex problems. In this article, we will see the difference between two such algorithms which are backtracking and branch and bound technique. Before getting into the differences, lets first understand each of these algorithms. Backtracking: Backtracking is a general algor
4 min read
Branch and Bound meaning in DSA
Branch and bound is an algorithmic technique used in computer science to solve optimization problems. Branch and bound is a systematic way of exploring all possible solutions to a problem by dividing the problem space into smaller sub-problems and then applying bounds or constraints to eliminate certain subproblems from consideration. Characteristi
3 min read
Branch and Bound Algorithm
The Branch and Bound Algorithm is a method used in combinatorial optimization problems to systematically search for the best solution. It works by dividing the problem into smaller subproblems, or branches, and then eliminating certain branches based on bounds on the optimal solution. This process continues until the best solution is found or all b
1 min read
Why do we use branch and bound algorithm?
The Branch and Bound algorithm is used to solve optimization problems where the goal is to find the best solution out of all possible solutions. It is efficient as it eliminates the need to check all solutions by ruling out those that cannot possibly lead to the best solution. What is Branch and Bound Algorithm?The Branch and Bound algorithm is a m
3 min read
Which strategy can be used to solve branch and bound problem?
Branch and Bound problem can be solved using different strategies such as Least Cost (LC) Search, Breadth-First Search (BFS) and Depth-First Search (DFS). These strategies help traverse the state space tree effectively, ensuring optimal solutions. Branch and bound is a problem-solving technique used in optimization problems to find the best possibl
2 min read
Minimize cost to connect the graph by connecting any pairs of vertices having cost at least 0
Given a disconnected graph G with N vertices and M edges and an array cost[] corresponding to each vertex, the task is to find the minimum cost to make the graph by connecting any pairs of vertices having the cost of vertices at least 0 and the cost of connecting those pair of vertices is the sum of the cost of individual vertices. If it is impossi
15+ min read
Minimum Cost using Dijkstra by Modifying Cost of an Edge
Given an undirected weighted graph of N nodes and M edges in the form of a tuple lets say {X, Y, Z} such that there is an edge with cost Z between X and Y. We are supposed to compute the minimum cost of traversal from node 1 to N. However, we can perform one operation before the traversal such that we can reduce the cost of any edge lets say, C to
15 min read
Minimize cost to buy N elements using given cost Array
Given 2 arrays num[] and cost[] containing the number of elements and the cost to buy that many elements respectively. {i.e. cost[i] is the cost to buy num[i] elements}. The task is to minimize the cost to buy exactly N elements. Examples: Input: num[] = [1, 2, 10, 50], cost[] = [400, 750, 3250, 15000], N = 7Output: 2650Explanation: The minimum amo
15+ min read
Queries to find the Lower Bound of K from Prefix Sum Array with updates using Fenwick Tree
Given an array A[ ] consisting of non-negative integers and a matrix Q[ ][ ] consisting of queries of the following two types: (1, l, val): Update A[l] to A[l] + val.(2, K): Find the lower_bound of K in the prefix sum array of A[ ]. If the lower_bound does not exist, print -1. The task for each query of the second type is to print the index of the
14 min read
Next Greater Element | Set 2 (Using Upper Bound)
Given an array arr[ ] of n integers. The task is to find the first greater element for every array element in the array using upper_bound( ) function. If there is no greater element possible for any array element return -1. Examples : Input: n = 7, arr[ ] = {4, 7, 3, 1, 3, 2, 5}Output: 7 -1 4 4 4 4 7 Explanation : First greater element for first, t
8 min read
Count pairs (p, q) such that p occurs in array at least q times and q occurs at least p times
Given an array arr[], the task is to count unordered pairs of positive integers (p, q) such that p occurs in the array at least q times and q occurs at least p times. Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: 1 (1, 1) is the only valid pair. Input: arr[] = {3, 3, 2, 2, 2} Output: 2 (2, 3) and (2, 2) are the only possible pairs. Approach: The
8 min read
Minimize cost to convert all 0s to 1s with cost of converting 0s group be X and that of 1 be X/3
Given binary string str, consisting of only two characters '1' and '0', and an integer X, the task is to calculate the minimum cost to convert all the characters to '1'. The cost to convert one '0' to '1' is given as X and the cost to convert one '1' to '0' is X / 3. If a '0' is converted to '1' then all the 0s adjacently connected to it as a group
9 min read
Maximize cost of segment having weight at most K from given weight and cost of N items
Given two arrays W[] and C[] containing weight and cost of N (1 to N) items respectively, and an integer K, find a segment from 1 to N, such that the total weight of the segment is at most K and the total cost is maximum. Print the cost of this segment. Examples: Input: N = 6, K = 20, W[] = {9, 7, 6, 5, 8, 4}, C[] = {7, 1, 3, 6, 8, 3}Output: 17Expl
12 min read
Minimize cost to travel from source to destination in a Matrix based on given row change and column change cost
Given an M*N grid, and given an array startPos[], indicating that the starting position is the cell (startPos[0], startPos[1]) and the array homePos[] indicating its destination is at the cell's (homePos[0], homePos[1]). From any cell movement is allowed only in four directions: left, right, up, and down, and cannot go outside the boundary. There a
7 min read
Minimum Cost To set Digital Clock Timer with given movement and push cost
Given integers A, B and N. The task is to minimize the cost to set N seconds in a digital clock where time is represented in the following format: at most 99 minutes and 99 secondsat least 1 secondThe first two digits represent minutes and the last two minutes represent seconds.It prepends 0 if less than 4 digits are pressed to set time A is the co
14 min read
Minimize cost by splitting given Array into subsets of size K and adding highest K/2 elements of each subset into cost
Given an array arr[] of N integers and an integer K, the task is to calculate the minimum cost by spilling the array elements into subsets of size K and adding the maximum ⌈K/2⌉ elements into the cost. Note: ⌈K/2⌉ means ceiling value of K/2. Examples: Input: arr[] = {1, 1, 2, 2}, K = 2Output: 3Explanation: The given array elements can be divided in
5 min read
Minimum cost to complete given tasks if cost of 1, 7 and 30 days are given
Given a sorted array arr[] consisting of N positive integers such that arr[i] represent the days in which a worker will work and an array cost[] of size 3 representing the salary paid to the workers for 1 day, 7 days and 30 days respectively, the task is to find the minimum cost required to have a worker for all the given days in arr[]. Examples: I
15+ min read
Construct a distinct elements array with given size, sum and element upper bound
Given N, size of the original array, SUM total sum of all elements present in the array and K such that no element in array is greater than K, construct the original array where all elements in the array are unique. If there is no solution, print "Not Possible". Note: All elements should be positive. Examples: Input: N = 3, SUM = 15, K = 8 Output:
10 min read
Lower and Upper Bound Theory
Lower and upper bound theory is a mathematical concept that involves finding the smallest and largest possible values for a quantity, given certain constraints or conditions. It is often used in optimization problems, where the goal is to find the maximum or minimum value of a function subject to certain constraints. In mathematical terms, the lowe
15+ min read
Minimum days to make Array elements with value at least K sum at least X
Given two integers X, K, and two arrays arr[] and R[] both consisting of N positive integers where R[i] denotes the amount by which arr[i] increases in one day, the task is to find the minimum number of days after which the sum of array elements having value greater than or equal to K becomes at least X. Examples: Input: X = 100, K = 45, arr[] = {2
9 min read
Smallest integer having at least K prime divisors with difference between each factor at least D
Given two integers D and K. The task is to find the smallest number N which has at least K prime divisors and the difference between each pair of divisors is at least D. Examples Input: D = 3, K = 2Output: 55Explanation: It is smallest number which has 4 divisors 1 and 2 prime divisors 5, 11 and their difference between any of the pair is D. Input:
7 min read