The Wayback Machine - https://web.archive.org/web/20250128025939/https://www.geeksforgeeks.org/connect-n-ropes-minimum-cost/
Open In App

Connect n ropes with minimum cost

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

Given an array arr[] of rope lengths, connect all ropes into a single rope with the minimum total cost. The cost to connect two ropes is the sum of their lengths.

Examples:

Input: arr[] = [4, 3, 2, 6]
Output: 29
Explanation: We can connect the ropes in following ways.
1) First connect ropes of lengths 2 and 3. Which makes the array [4, 5, 6]. Cost of this operation 2 + 3 = 5.
2) Now connect ropes of lengths 4 and 5. Which makes the array [9, 6]. Cost of this operation 4 + 5 = 9.
3) Finally connect the two ropes and all ropes have connected. Cost of this operation 9 + 6 =15. Total cost is 5 + 9 + 15 = 29. This is the optimized cost for connecting ropes.

Other ways of connecting ropes would always have same or more cost. For example, if we connect 4 and 6 first (we get three rope of 3, 2 and 10), then connect 10 and 3 (we gettwo rope of 13 and 2). Finally we connect 13 and 2. Total cost in this way is 10 + 13 + 15 = 38.

Connect-n-ropes-with-minimum-cost

Input: arr[] = [10]
Output: 0
Explanation: Since there is only one rope, no connections are needed, so the cost is 0.

Approach:

The idea is to connect the smallest two ropes first, as the lengths of the ropes that are picked early are included more than once in the total cost. This approach is similar to the concept used in Huffman Coding, where the smaller elements are combined earlier, which results in a smaller cost for subsequent operations.

To implement the idea, use a min-heap (priority queue) and push all elements into it. While the heap contains more than one element, repeatedly extract the two smallest values, add them, and insert the sum back into the heap. Maintain a variable to track the total cost, incrementing it by the sum of the extracted values at each step. Once the process is complete, return the total cost.

Below is the implementation of the above approach:

C++
// C++ program for connecting n rope
// with minimum cost using min-heap
#include <bits/stdc++.h>
using namespace std;

int minCost(vector<int> &arr) {

    // Create a priority queue
    // By default 'less' is used which is for decreasing
    // order and 'greater' is used for increasing order
    priority_queue<int, vector<int>,
               greater<int>> pq(arr.begin(), arr.end());

    // Initialize result
    int res = 0;

    // While size of priority queue is more than 1
    while (pq.size() > 1) {

        // Extract shortest two ropes from pq
        int first = pq.top();
        pq.pop();
        int second = pq.top();
        pq.pop();

        // Connect the ropes: update result and
        // insert the new rope to pq
        res += first + second;
        pq.push(first + second);
    }

    return res;
}

int main() {

    vector<int> arr = {4, 3, 2, 6};
    cout << minCost(arr);
    return 0;
}
Java
// Java program for connecting n ropes
// with minimum cost using min-heap
import java.util.PriorityQueue;

class GfG {
  
     public static int minCost(int[] arr) {
      
        // Create a priority queue
        // By default, the priority queue is in
        // increasing order
        PriorityQueue<Integer> pq = new PriorityQueue<>();
       
        for (int num : arr) {
            pq.add(num);
        }

        // Initialize result
        int res = 0;

        // While size of priority queue is more than 1
        while (pq.size() > 1) {
          
            // Extract shortest two ropes from pq
            int first = pq.poll();
            int second = pq.poll();

            // Connect the ropes: update result and
            // insert the new rope to pq
            res += first + second;
            pq.add(first + second);
        }

        return res;
    }

    public static void main(String[] args) {
      
        int[] arr = {4, 3, 2, 6};
        System.out.println(minCost(arr));
    }
}
Python
# Python program for connecting n ropes
# with minimum cost using min-heap
import heapq

def minCost(arr):
  
    # Create a priority queue
    # By default, heapq provides a min-heap
    heapq.heapify(arr)

    # Initialize result
    res = 0

    # While size of priority queue is more than 1
    while len(arr) > 1:
      
        # Extract shortest two ropes from pq
        first = heapq.heappop(arr)
        second = heapq.heappop(arr)

        # Connect the ropes: update result and
        # insert the new rope to pq
        res += first + second
        heapq.heappush(arr, first + second)

    return res

if __name__ == "__main__":
  
    arr = [4, 3, 2, 6]
    print(minCost(arr))
C#
// C# program for connecting n ropes
// with minimum cost using min-heap
using System;
using System.Collections.Generic;

class GfG {
  
    static int minCost(int[] arr) {
      
        // Create a priority queue
        SortedSet<(int Value, int Index)> pq = 
                      new SortedSet<(int, int)>();
      
        for (int i = 0; i < arr.Length; i++) {
            pq.Add((arr[i], i));
        }

        // Initialize result
        int res = 0;

        // While size of priority queue is more than 1
        while (pq.Count > 1) {
          
            // Extract shortest two ropes from pq
            int first = pq.Min.Value;
            pq.Remove(pq.Min);

            int second = pq.Min.Value;
            pq.Remove(pq.Min);

            // Connect the ropes: update result and
            // insert the new rope to pq
            res += first + second;
            pq.Add((first + second, pq.Count + 1));
        }

        return res;
    }

    static void Main(string[] args) {
      
        int[] arr = { 4, 3, 2, 6 };
        Console.WriteLine(minCost(arr));
    }
}
JavaScript
// JavaScript program for connecting n ropes
// with minimum cost using min-heap

function minCost(arr) {
    // Create a min-heap and add all elements
    const pq = new MinHeap();
    arr.forEach(num => pq.push(num));

    // Initialize result
    let res = 0;

    // While size of priority queue is more than 1
    while (pq.size() > 1) {

        // Extract shortest two ropes from pq
        const first = pq.pop();
        const second = pq.pop();

        // Connect the ropes: update result and
        // insert the new rope to pq
        res += first + second;
        pq.push(first + second);
    }

    return res;
}

class MinHeap {
    constructor() {
        this.heap = [];
    }

    // Insert a value into the heap
    push(val) {
        this.heap.push(val);
        this.heapifyUp();
    }

    // Remove and return the smallest element
    pop() {
        if (this.heap.length === 1) {
            return this.heap.pop();
        }
        const root = this.heap[0];
        this.heap[0] = this.heap.pop();
        this.heapifyDown();
        return root;
    }

    // Return the smallest element without removing it
    top() {
        return this.heap[0];
    }

    // Return the size of the heap
    size() {
        return this.heap.length;
    }

    // Restore the heap property upwards
    heapifyUp() {
        let index = this.heap.length - 1;
        while (index > 0) {
            const parentIndex = Math.floor(
                (index - 1) / 2
            );
            if (
                this.heap[index] >=
                this.heap[parentIndex]
            ) {
                break;
            }
            [
                this.heap[index],
                this.heap[parentIndex]
            ] = [
                this.heap[parentIndex],
                this.heap[index]
            ];
            index = parentIndex;
        }
    }

    // Restore the heap property downwards
    heapifyDown() {
        let index = 0;
        const size = this.heap.length;
        while (true) {
            const leftChild = 2 * index + 1;
            const rightChild = 2 * index + 2;
            let smallest = index;

            if (
                leftChild < size &&
                this.heap[leftChild] <
                this.heap[smallest]
            ) {
                smallest = leftChild;
            }

            if (
                rightChild < size &&
                this.heap[rightChild] <
                this.heap[smallest]
            ) {
                smallest = rightChild;
            }

            if (smallest === index) {
                break;
            }

            [
                this.heap[index],
                this.heap[smallest]
            ] = [
                this.heap[smallest],
                this.heap[index]
            ];
            index = smallest;
        }
    }
}

const arr = [4, 3, 2, 6];
console.log(minCost(arr));

Output
29

Time Complexity: O(n log n), where n is the size of the array. Each insertion or deletion in the heap takes O(log n)
Space Complexity: O(n), for storing all elements in the heap.



Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg