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

Connect n ropes with minimum cost

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

Given are N ropes of different lengths, the task is to connect these ropes into one rope with minimum cost, such that the cost to connect two ropes is equal to the sum of their lengths.

Examples:

Input: arr[] = {4,3,2,6} , N = 4
Output: 29
Explanation: 

  1. First, connect ropes of lengths 2 and 3. Now we have three ropes of lengths 4, 6, and 5. 
  2. Now connect ropes of lengths 4 and 5. Now we have two ropes of lengths 6 and 9. 
  3. Finally connect the two ropes and all ropes have connected.

                 

Input: arr[] = {1, 2, 3} , N = 3
Output: 9
Explanation: 

  1. First, connect ropes of lengths 1 and 2. Now we have two ropes of lengths 3 and 3. 
  2. Finally connect the two ropes and all ropes have connected.

We strongly recommend that you click here and practice it, before moving on to the solution.

Approach:

 If we observe the above problem closely, we can notice that the lengths of the ropes which are picked first are included more than once in the total cost. Therefore, the idea is to connect the smallest two ropes first and recur for the remaining ropes. This approach is similar to Huffman Coding. We put the smallest ropes down the tree so they can be repeated multiple times rather than the longer ones.

Follow the steps mentioned below to implement the idea:

  1. Declare a priority queue and push all the elements in it.
  2. Do following while the number of elements in min-heap is greater than one. 
    1. Extract the minimum and second minimum from min-heap
    2. Add the above two extracted values and insert the added value to the min-heap.
    3. Maintain a variable for total cost and keep incrementing it by the sum of extracted values.
  3. Return the value of total cost.

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>

using namespace std;

int minCost(int arr[], int n)
{
    // Create a priority queue
    // https://www.geeksforgeeks.org/priority-queue-in-cpp-stl/
    // 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, arr + n);

    // 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;
}

// Driver program to test above function
int main()
{
    int len[] = { 4, 3, 2, 6 };
    int size = sizeof(len) / sizeof(len[0]);
    cout << "Total cost for connecting ropes is "
         << minCost(len, size);
    return 0;
}
Java
// Java program to connect n
// ropes with minimum cost
import java.util.*;

class ConnectRopes {
    static int minCost(int arr[], int n)
    {
        // Create a priority queue
        PriorityQueue<Integer> pq
            = new PriorityQueue<Integer>();

        // Adding items to the pQueue
        for (int i = 0; i < n; i++) {
            pq.add(arr[i]);
        }

        // 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;
    }

    // Driver program to test above function
    public static void main(String args[])
    {
        int len[] = { 4, 3, 2, 6 };
        int size = len.length;
        System.out.println("Total cost for connecting"
                           + " ropes is "
                           + minCost(len, size));
    }
}
Python
# Python3 program to connect n
# ropes with minimum cost
import heapq


def minCost(arr, n):

    # Create a priority queue out of the
    # given list
    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 arr
        first = heapq.heappop(arr)
        second = heapq.heappop(arr)

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

    return res


# Driver code
if __name__ == '__main__':

    lengths = [4, 3, 2, 6]
    size = len(lengths)

    print("Total cost for connecting ropes is " +
          str(minCost(lengths, size)))
C#
// C# program to connect n
// ropes with minimum cost
using System;
using System.Collections.Generic;
public class ConnectRopes {
    static int minCost(int[] arr, int n)
    {
        // Create a priority queue
        List<int> pq = new List<int>();

        // Adding items to the pQueue
        for (int i = 0; i < n; i++) {
            pq.Add(arr[i]);
        }

        // Initialize result
        int res = 0;

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

            // Extract shortest two ropes from pq
            int first = pq[0];
            int second = pq[1];
            pq.RemoveRange(0, 2);

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

    // Driver program to test above function
    public static void Main(String[] args)
    {
        int[] len = { 4, 3, 2, 6 };
        int size = len.Length;
        Console.WriteLine("Total cost for connecting"
                          + " ropes is "
                          + minCost(len, size));
    }
}
JavaScript
// JavaScript program to connect n
// ropes with minimum cost

function minCost(arr,n)
{
    // Create a priority queue
        let pq = [];
  
        // Adding items to the pQueue
        for (let i = 0; i < n; i++) {
            pq.push(arr[i]);
        }    
          
        pq.sort(function(a,b){return a-b;});
        
        // Initialize result
        let res = 0;
  
        // While size of priority queue
        // is more than 1
        while (pq.length > 1) {
            // Extract shortest two ropes from pq
            let first = pq.shift();
            let second = pq.shift();
  
            // Connect the ropes: update result
            // and insert the new rope to pq
            res += first + second;
            pq.push(first + second);
            pq.sort(function(a,b){return a-b;});
        }
  
        return res;
}

// Driver program to test above function
let len = [4, 3, 2, 6];
let size = len.length;
console.log("Total cost for connecting"
                           + " ropes is " + minCost(len, size));

Output
Total cost for connecting ropes is 29

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



Previous Article
Next Article

Similar Reads

Article Tags :
Practice Tags :
three90RightbarBannerImg