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

Connect n ropes with minimum cost

Last Updated : 24 Dec, 2024
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.

C++
// C++ program for connecting n rope
// with minimum cost using min-heap
//(priority queue)

#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
// (priority queue)

import java.util.PriorityQueue;

class GfG {
  
    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
# (priority queue)

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
// (priority queue)

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
// (priority queue)

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

    // Insert a value into the heap
    insert(value) {
        this.heap.push(value);
        this._heapifyUp(this.heap.length - 1);
    }

    // Extract the minimum value from the heap
    extractMin() {
        if (this.heap.length === 1) return this.heap.pop();

        const min = this.heap[0];
        this.heap[0] = this.heap.pop();
        this._heapifyDown(0);
        return min;
    }

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

    // Helper method to maintain the heap property on insertion
    _heapifyUp(index) {
        let parent = Math.floor((index - 1) / 2);
        while (index > 0 && this.heap[index] < this.heap[parent]) {
            [this.heap[index], this.heap[parent]] =
                [this.heap[parent], this.heap[index]];
            index = parent;
            parent = Math.floor((index - 1) / 2);
        }
    }

    // Helper method to maintain the heap property on extraction
    _heapifyDown(index) {
        let smallest = index;
        const left = 2 * index + 1;
        const right = 2 * index + 2;

        if (left < this.heap.length && this.heap[left] < this.heap[smallest]) {
            smallest = left;
        }

        if (right < this.heap.length && this.heap[right] < this.heap[smallest]) {
            smallest = right;
        }

        if (smallest !== index) {
            [this.heap[index], this.heap[smallest]] =
                [this.heap[smallest], this.heap[index]];
            this._heapifyDown(smallest);
        }
    }
}

// Function to calculate the minimum cost of connecting ropes
function minCost(arr) {
    if (arr.length <= 1) return 0;

    // Initialize the heap with the elements in arr
    const minHeap = new MinHeap();
    for (const num of arr) {
        minHeap.insert(num);
    }

    let totalCost = 0;

    // Continue combining ropes until only one remains
    while (minHeap.size() > 1) {
        const val1 = minHeap.extractMin();
        const val2 = minHeap.extractMin();
        const combinedCost = val1 + val2;
        totalCost += combinedCost;
        minHeap.insert(combinedCost);
    }

    return totalCost;
}

// driver code
const ropes = [4, 3, 2, 6];
console.log(minCost(ropes));

Output
29

Time Complexity: O(n*log(n))
Auxiliary Space: O(n)



Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg