Open In App

Connect n ropes with minimum cost

Last Updated : 19 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Connect N ropes with minimum cost using Min-Heap

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.

Illustration:

  • First, we will connect ropes of lengths 2 and 3 because they are the smallest. Now we have three ropes left of lengths 4, 6, and 5.
  • Now we connect ropes of lengths 4 and 5. Now we have two ropes of lengths 6 and 9.
  • Finally, we will connect the two ropes so that all ropes are connected.

  • The total cost contains the sum of depth of each value. For array [ 2, 3, 4, 6 ] the sum is equal to (2 * 3) + (3 * 3) + (4 * 2) + (6 * 1) = 29 (According to the diagram). 

Algorithm: Follow the steps mentioned below to implement the idea:

  • Create a min-heap and insert all lengths into the min-heap.
  • Do following while the number of elements in min-heap is greater than one. 
    • Extract the minimum and second minimum from min-heap
    • Add the above two extracted values and insert the added value to the min-heap.
    • Maintain a variable for total cost and keep incrementing it by the sum of extracted values.
  • Return the value of total cost.

Below is the implementation of the above approach:

C++




// C++ program for connecting
// n ropes with minimum cost
#include <bits/stdc++.h>
 
using namespace std;
 
// A Min Heap: Collection of min heap nodes
struct MinHeap {
    unsigned size; // Current size of min heap
    unsigned capacity; // capacity of min heap
    int* harr; // Array of minheap nodes
};
 
// A utility function to create
// a min-heap of a given capacity
struct MinHeap* createMinHeap(unsigned capacity)
{
    struct MinHeap* minHeap = new MinHeap;
    minHeap->size = 0; // current size is 0
    minHeap->capacity = capacity;
    minHeap->harr = new int[capacity];
    return minHeap;
}
 
// A utility function to swap two min heap nodes
void swapMinHeapNode(int* a, int* b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}
 
// The standard minHeapify function.
void minHeapify(struct MinHeap* minHeap, int idx)
{
    int smallest = idx;
    int left = 2 * idx + 1;
    int right = 2 * idx + 2;
 
    if (left < minHeap->size
        && minHeap->harr[left] < minHeap->harr[smallest])
        smallest = left;
 
    if (right < minHeap->size
        && minHeap->harr[right] < minHeap->harr[smallest])
        smallest = right;
 
    if (smallest != idx) {
        swapMinHeapNode(&minHeap->harr[smallest],
                        &minHeap->harr[idx]);
        minHeapify(minHeap, smallest);
    }
}
 
// A utility function to check
// if size of heap is 1 or not
int isSizeOne(struct MinHeap* minHeap)
{
    return (minHeap->size == 1);
}
 
// A standard function to extract
// minimum value node from heap
int extractMin(struct MinHeap* minHeap)
{
    int temp = minHeap->harr[0];
    minHeap->harr[0] = minHeap->harr[minHeap->size - 1];
    --minHeap->size;
    minHeapify(minHeap, 0);
    return temp;
}
 
// A utility function to insert
// a new node to Min Heap
void insertMinHeap(struct MinHeap* minHeap, int val)
{
    ++minHeap->size;
    int i = minHeap->size - 1;
    while (i && (val < minHeap->harr[(i - 1) / 2])) {
        minHeap->harr[i] = minHeap->harr[(i - 1) / 2];
        i = (i - 1) / 2;
    }
    minHeap->harr[i] = val;
}
 
// A standard function to build min-heap
void buildMinHeap(struct MinHeap* minHeap)
{
    int n = minHeap->size - 1;
    int i;
    for (i = (n - 1) / 2; i >= 0; --i)
        minHeapify(minHeap, i);
}
 
// Creates a min-heap of capacity
// equal to size and inserts all values
// from len[] in it. Initially, size
// of min heap is equal to capacity
struct MinHeap* createAndBuildMinHeap(int len[], int size)
{
    struct MinHeap* minHeap = createMinHeap(size);
    for (int i = 0; i < size; ++i)
        minHeap->harr[i] = len[i];
    minHeap->size = size;
    buildMinHeap(minHeap);
    return minHeap;
}
 
// The main function that returns
// the minimum cost to connect n
// ropes of lengths stored in len[0..n-1]
int minCost(int len[], int n)
{
    int cost = 0; // Initialize result
 
    // Create a min heap of capacity
    // equal to n and put all ropes in it
    struct MinHeap* minHeap = createAndBuildMinHeap(len, n);
 
    // Iterate while size of heap doesn't become 1
    while (!isSizeOne(minHeap)) {
        // Extract two minimum length
        // ropes from min heap
        int min = extractMin(minHeap);
        int sec_min = extractMin(minHeap);
 
        cost += (min + sec_min); // Update total cost
 
        // Insert a new rope in min heap
        // with length equal to sum
        // of two extracted minimum lengths
        insertMinHeap(minHeap, min + sec_min);
    }
 
    // Finally return total minimum
    // cost for connecting all ropes
    return cost;
}
 
// Driver program to test above functions
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
 
// A class for Min Heap
class MinHeap {
    int[] harr; // Array of elements in heap
    int heap_size; // Current number of elements in min heap
    int capacity; // maximum possible size of min heap
 
    // Constructor: Builds a heap from
    // a given array a[] of given size
    public MinHeap(int a[], int size)
    {
        heap_size = size;
        capacity = size;
        harr = a;
        int i = (heap_size - 1) / 2;
        while (i >= 0) {
            MinHeapify(i);
            i--;
        }
    }
 
    // A recursive method to heapify a subtree
    // with the root at given index
    // This method assumes that the subtrees
    // are already heapified
    void MinHeapify(int i)
    {
        int l = left(i);
        int r = right(i);
        int smallest = i;
        if (l < heap_size && harr[l] < harr[i])
            smallest = l;
        if (r < heap_size && harr[r] < harr[smallest])
            smallest = r;
        if (smallest != i) {
            swap(i, smallest);
            MinHeapify(smallest);
        }
    }
 
    int parent(int i) { return (i - 1) / 2; }
 
    // to get index of left child of node at index i
    int left(int i) { return (2 * i + 1); }
 
    // to get index of right child of node at index i
    int right(int i) { return (2 * i + 2); }
 
    // Method to remove minimum element (or root) from min
    // heap
    int extractMin()
    {
        if (heap_size <= 0)
            return Integer.MAX_VALUE;
        if (heap_size == 1) {
            heap_size--;
            return harr[0];
        }
 
        // Store the minimum value, and remove it from heap
        int root = harr[0];
        harr[0] = harr[heap_size - 1];
        heap_size--;
        MinHeapify(0);
 
        return root;
    }
 
    // Inserts a new key 'k'
    void insertKey(int k)
    {
        if (heap_size == capacity) {
            System.out.println(
                "Overflow: Could not insertKey");
            return;
        }
 
        // First insert the new key at the end
        heap_size++;
        int i = heap_size - 1;
        harr[i] = k;
 
        // Fix the min heap property if it is violated
        while (i != 0 && harr[parent(i)] > harr[i]) {
            swap(i, parent(i));
            i = parent(i);
        }
    }
 
    // A utility function to check
    // if size of heap is 1 or not
    boolean isSizeOne() { return (heap_size == 1); }
 
    // A utility function to swap two elements
    void swap(int x, int y)
    {
        int temp = harr[x];
        harr[x] = harr[y];
        harr[y] = temp;
    }
 
    // The main function that returns the
    // minimum cost to connect n ropes of
    // lengths stored in len[0..n-1]
    static int minCost(int len[], int n)
    {
        int cost = 0; // Initialize result
 
        // Create a min heap of capacity equal
        // to n and put all ropes in it
        MinHeap minHeap = new MinHeap(len, n);
 
        // Iterate while size of heap doesn't become 1
        while (!minHeap.isSizeOne()) {
            // Extract two minimum length ropes from min
            // heap
            int min = minHeap.extractMin();
            int sec_min = minHeap.extractMin();
 
            cost += (min + sec_min); // Update total cost
 
            // Insert a new rope in min heap with length
            // equal to sum of two extracted minimum lengths
            minHeap.insertKey(min + sec_min);
        }
 
        // Finally return total minimum
        // cost for connecting all ropes
        return cost;
    }
 
    // Driver code
    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));
    }
};
 
// This code is contributed by shubham96301


C#




// C# program to connect n ropes with minimum cost
using System;
 
// A class for Min Heap
class MinHeap {
    int[] harr; // Array of elements in heap
    int heap_size; // Current number of elements in min heap
    int capacity; // maximum possible size of min heap
 
    // Constructor: Builds a heap from
    // a given array a[] of given size
    public MinHeap(int[] a, int size)
    {
        heap_size = size;
        capacity = size;
        harr = a;
        int i = (heap_size - 1) / 2;
        while (i >= 0) {
            MinHeapify(i);
            i--;
        }
    }
 
    // A recursive method to heapify a subtree
    // with the root at given index
    // This method assumes that the subtrees
    // are already heapified
    void MinHeapify(int i)
    {
        int l = left(i);
        int r = right(i);
        int smallest = i;
        if (l < heap_size && harr[l] < harr[i])
            smallest = l;
        if (r < heap_size && harr[r] < harr[smallest])
            smallest = r;
        if (smallest != i) {
            swap(i, smallest);
            MinHeapify(smallest);
        }
    }
 
    int parent(int i) { return (i - 1) / 2; }
 
    // to get index of left child of node at index i
    int left(int i) { return (2 * i + 1); }
 
    // to get index of right child of node at index i
    int right(int i) { return (2 * i + 2); }
 
    // Method to remove minimum element (or root) from min
    // heap
    int extractMin()
    {
        if (heap_size <= 0)
            return int.MaxValue;
        if (heap_size == 1) {
            heap_size--;
            return harr[0];
        }
 
        // Store the minimum value, and remove it from heap
        int root = harr[0];
        harr[0] = harr[heap_size - 1];
        heap_size--;
        MinHeapify(0);
 
        return root;
    }
 
    // Inserts a new key 'k'
    void insertKey(int k)
    {
        if (heap_size == capacity) {
            Console.WriteLine(
                "Overflow: Could not insertKey");
            return;
        }
 
        // First insert the new key at the end
        heap_size++;
        int i = heap_size - 1;
        harr[i] = k;
 
        // Fix the min heap property if it is violated
        while (i != 0 && harr[parent(i)] > harr[i]) {
            swap(i, parent(i));
            i = parent(i);
        }
    }
 
    // A utility function to check
    // if size of heap is 1 or not
    Boolean isSizeOne() { return (heap_size == 1); }
 
    // A utility function to swap two elements
    void swap(int x, int y)
    {
        int temp = harr[x];
        harr[x] = harr[y];
        harr[y] = temp;
    }
 
    // The main function that returns the
    // minimum cost to connect n ropes of
    // lengths stored in len[0..n-1]
    static int minCost(int[] len, int n)
    {
        int cost = 0; // Initialize result
 
        // Create a min heap of capacity equal
        // to n and put all ropes in it
        MinHeap minHeap = new MinHeap(len, n);
 
        // Iterate while size of heap doesn't become 1
        while (!minHeap.isSizeOne()) {
            // Extract two minimum length ropes from min
            // heap
            int min = minHeap.extractMin();
            int sec_min = minHeap.extractMin();
 
            cost += (min + sec_min); // Update total cost
 
            // Insert a new rope in min heap with length
            // equal to sum of two extracted minimum lengths
            minHeap.insertKey(min + sec_min);
        }
 
        // Finally return total minimum
        // cost for connecting all ropes
        return cost;
    }
 
    // Driver code
    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));
    }
};
 
// This code is contributed by Arnab Kundu


Python3




# 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)))
 
# This code is contributed by shivampatel5


Javascript




<script>
 
// 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;
document.write("Total cost for connecting"
                           + " ropes is " + minCost(len, size));
 
// This code is contributed by avanitrachhadiya2155
 
</script>


Output

Total cost for connecting ropes is 29

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

Connect N ropes with minimum cost using Pre Defined Function

In this approach, we use the predefined priority queue which is already available. The approach and algorithm remain the same. The min heap is replaced by a priority queue.

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
    // 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));
    }
}
// This code is contributed by yash_pec


Python3




# 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)))
 
# This code is contributed by shivampatel5


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));
    }
}
 
// This code is contributed by Rajput-Ji


Javascript




<script>
 
// 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;
document.write("Total cost for connecting"
                           + " ropes is " + minCost(len, size));
 
// This code is contributed by avanitrachhadiya2155
 
</script>


Output

Total cost for connecting ropes is 29

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



Previous Article
Next Article

Similar Reads

Maximum length of all possible K equal length ropes generated by cutting N ropes
Given an array arr[] consisting of N positive integers representing the lengths of N ropes and a positive integer K, the task is to find the maximum length of the rope that has a frequency of at least K by cutting any ropes in any number of pieces. Examples: Input: arr[] = {5, 2, 7, 4, 9}, K = 5Output: 4Explanation:Below are the possible cutting of
8 min read
Maximize ropes of consecutive length possible by connecting given ropes
Given an array A[ ] of size N where each array element represents the length of a rope, the task is to find the number of ropes of consecutive length that can be created by connecting given ropes starting from length 1. Examples : Input: N = 5, A[ ] = {1, 2, 7, 1, 1} Output: 5 Explanation: Length | Ropes 1 | [1] 2 | [1, 1] 3 | [1, 2] 4 | [1, 2, 1]
6 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 to connect all cities
There are n cities and there are roads in between some of the cities. Somehow all the roads are damaged simultaneously. We have to repair the roads to connect the cities again. There is a fixed cost to repair a particular road. Find out the minimum cost to connect all the cities by repairing roads. Input is in matrix(city) form, if city[i][j] = 0 t
14 min read
Minimum cost required to connect all houses in a city
Given a 2D array houses[][] consisting of N 2D coordinates {x, y} where each coordinate represents the location of each house, the task is to find the minimum cost to connect all the houses of the city. Cost of connecting two houses is the Manhattan Distance between the two points (xi, yi) and (xj, yj) i.e., |xi - xj| + |yi - yj|, where |p| denotes
10 min read
Minimum cost to connect weighted nodes represented as array
Given an array of N elements(nodes), where every element is weight of that node.Connecting two nodes will take a cost of product of their weights.You have to connect every node with every other node(directly or indirectly).Output the minimum cost required.Examples: Input : a[] = {6, 2, 1, 5} Output : 13 Explanation : Here, we connect the nodes as f
4 min read
N consecutive ropes problem
Given N ropes, each rope has a length associated with it. At a time, only two consecutive small ropes tied at end form a large rope and cost of forming sum of their length. Find the minimum cost when all ropes are tied to form a single rope. Examples: Input: arr[] = {7, 6, 8, 6, 1, 1} Output: 68 {7, 6, 8, 6, 1, 1} - {7, 6, 8, 6, 2}, cost = 2 {7, 6,
9 min read
STL Ropes in C++
Ropes are scalable string implementation. They are designed for efficient operation that involves the string as a whole. Operations such as assignment, concatenation, and sub-string take time that is nearly independent of the length of the string. A rope is a binary tree where each leaf (end node) holds a string and a length (also known as a “weigh
5 min read
Number of ways to use all the K ropes
Given two walls A, B with M, and N hooks respectively. You are also given K ropes. By using one rope you can connect one hook on wall A with another hook on wall B. One hook can connect with only one rope. Find the number of different ways you can use all the K ropes.Two ways that use the exact same set of hooks from wall A and wall B are considere
7 min read
Ropes left after every removal of smallest
Given an array of an integer of size, N. Array contains N ropes of length Ropes[i]. You have to perform a cut operation on ropes such that all of them are reduced by the length of the smallest rope. Display the number of ropes left after every cut. Perform operations till the length of each rope becomes zero. Note: IF no ropes left after a single o
8 min read
three90RightbarBannerImg