Skip to content

Commit c4c2a09

Browse files
add implementation for minimum cost to connect ropes using a priority queue
1 parent e4e9111 commit c4c2a09

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

26Heap/05minCostToMakeRope.cpp

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
//give a array of length of ropes find min cost to connect them if , length of rope == cost
4+
class Solution{
5+
public:
6+
int minCost(vector<int>& arr){
7+
priority_queue<int,vector<int>, greater<int>> pq;
8+
for(int ele:arr){
9+
pq.push(ele);
10+
}
11+
while(pq.size()>1){
12+
int x = pq.top(); pq.pop();
13+
int y = pq.top(); pq.pop();
14+
pq.push(x+y);
15+
cout<<"Cost : "<<x+y<<endl;
16+
}
17+
return pq.top();
18+
}
19+
};
20+
int main(){
21+
vector<int> arr {2,7,4,1,8};
22+
Solution* s = new Solution();
23+
cout<<s->minCost(arr);
24+
}

26Heap/05minCostToMakeRope.exe

175 KB
Binary file not shown.

0 commit comments

Comments
 (0)