- Related Questions & Answers
- Add minimum number to an array so that the sum becomes even in C programming
- How to I connect to wifi network on Android programmatically?
- Prim’s (Minimum Spanning Tree) MST Algorithm
- Kruskal’s (Minimum Spanning Tree) MST Algorithm
- Array element with minimum sum of absolute differences?
- Add minimum number to an array so that the sum becomes even in C++?
- How to find the minimum values of two or more fields in MySQL?
- Is there a way to retrieve the minimum value of fields in MySQL?
- Finding the minimum and maximum value from a string with numbers separated by hyphen in MySQL?
- C++ Program to Find the Minimum value of Binary Search Tree
- Find minimum value with MongoDB?
- Get maximum and minimum value in MongoDB?
- How to change the minimum value of a JSlider in Java?
- How to find the minimum value of an array in JavaScript?
- How to set minimum size limit for a JFrame in Java

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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: The lengths of the ropes: {4, 3, 2, 6, 5, 7, 12} Output: Total minimum cost: 103

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

#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); }

Total minimum cost: 103

Advertisements