-
Notifications
You must be signed in to change notification settings - Fork 0
/
25_minimum_cost_of_ropes.cpp
55 lines (46 loc) · 1.11 KB
/
25_minimum_cost_of_ropes.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
public:
//Function to return the minimum cost of connecting the ropes.
long long minCost(long long arr[], long long n) {
priority_queue<long long, vector<long long>, greater<long long> > pq;
for(int i=0; i<n; i++){
pq.push(arr[i]);
}
long long sum=0, num1=pq.top(), num2=pq.top();
pq.pop();
while(!pq.empty()){
if(num1<=pq.top()){
num1 = num1+pq.top();
pq.pop();
sum += num1;
}else{
pq.push(num1);
num1 = pq.top();
pq.pop();
}
}
return sum;
}
};
//{ Driver Code Starts.
int main() {
long long t;
cin >> t;
while (t--) {
long long n;
cin >> n;
long long i, a[n];
for (i = 0; i < n; i++) {
cin >> a[i];
}
Solution ob;
cout << ob.minCost(a, n) << endl;
}
return 0;
}
// } Driver Code Ends