Skip to content

Commit 1f59cf2

Browse files
authored
Create main.cpp
1 parent 1326793 commit 1f59cf2

File tree

1 file changed

+36
-0
lines changed
  • 25 - Greedy Algorithm Problems/07 - Minimum Cost of Ropes

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution {
2+
public:
3+
// Function to return the minimum cost of connecting the ropes.
4+
int minCost(vector<int>& arr) {
5+
// Create a min-heap (priority queue) to store the rope lengths
6+
priority_queue<int, vector<int>, greater<int>> pq;
7+
8+
// Push all the rope lengths into the priority queue
9+
for(int i = 0; i < arr.size(); i++) pq.push(arr[i]);
10+
11+
// Variable to store the total cost of connecting the ropes
12+
int totalCost = 0;
13+
14+
// Continue combining the two smallest ropes until only one rope remains
15+
while(pq.size() > 1){
16+
// Get the two smallest ropes from the heap
17+
int mini_1 = pq.top();
18+
pq.pop();
19+
20+
int mini_2 = pq.top();
21+
pq.pop();
22+
23+
// Calculate the cost of connecting the two smallest ropes
24+
int total = mini_1 + mini_2;
25+
26+
// Add this cost to the total cost
27+
totalCost += total;
28+
29+
// Push the new combined rope (total length) back into the priority queue
30+
pq.push(total);
31+
}
32+
33+
// Return the total cost of connecting all ropes
34+
return totalCost;
35+
}
36+
};

0 commit comments

Comments
 (0)