Connect n ropes with minimum cost

AlgorithmsMisc AlgorithmsData Structure

There are N ropes of given lengths. We have to connect with them. The cost of connecting one rope with other is the sum of their lengths. Our goal is to connect the N ropes with minimum cost.

This problem can be solved using a heap tree. We will create min heap to insert all different lengths first, then remove minimum and second minimum item from min heap, connect them and again insert into the heap tree. When the heap will hold only one element, we can stop the process and get the connected rope with minimum costs.

Input and Output

Input: 
The lengths of the ropes: {4, 3, 2, 6, 5, 7, 12}
Output: 
Total minimum cost: 103

Algorithm

findMinCost(array, n)

Input: List of rope lengths, number of entries in the list.

Output: Minimum cost to cut.

Begin
   minCost := 0
   fill priority queue with the array elements, (greater value is higher priority)
   while queue is not empty, do
      item1 := get item from queue and delete from queue
      item2 := get item from queue and delete from queue
      minCost := minCost + item1 + item2
      add (item1 + item2) into the queue
   done
   return minCost
End

Source Code (C++)

#include<iostream>
#include<queue>
#include<vector>
using namespace std;

int findMinimumCost(int arr[], int n) {
   //priority queue is set as whose value is bigger, have higher priority
   priority_queue< int, vector<int>, greater<int>>queue(arr, arr+n);

   int minCost = 0;

   while (queue.size() > 1) {              //when queue has more than one element
      int item1 = queue.top();            //item1 is the shortest element
      queue.pop();

      int item2 = queue.top();          //item2 is bigger than item1 but shorter then other
      queue.pop();

      minCost += item1 + item2;         //connect ropes and add them to the queue
      queue.push(item1 + item2);
   }
   return minCost;
}

int main() {
   int ropeLength[] = {4, 3, 2, 6, 5, 7, 12};
   int n = 7;
   cout << "Total minimum cost: " << findMinimumCost(ropeLength, n);
}

Output

Total minimum cost: 103
raja
Published on 12-Jul-2018 08:19:33
Advertisements