-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path00_RopeJoining.cpp
81 lines (70 loc) · 1.96 KB
/
00_RopeJoining.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// https://www.geeksforgeeks.org/problems/minimum-cost-of-ropes-1587115620/1
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution1
{
// Solution Using Max Heap: If we have to use max heap, we can negate all the elements of the given input array.
// [3, 4, 5] -> [-3, -4, -5];
// Now in max heap -3 would be on top and we can negate after popping.
public:
//Function to return the minimum cost of connecting the ropes.
long long minCost(long long arr[], long long n) {
// Max Heap
priority_queue<long long> pq;
long long cost = 0;
for(long long i = 0; i < n; ++i) {
pq.push((arr[i]) * (-1));
}
while(pq.size() > 1) {
long long first = pq.top();
pq.pop();
long long second = pq.top();
pq.pop();
cost += (first + second) * (-1);
pq.push((first+second));
}
return cost;
}
};
class Solution
// Solution using Min Heap:
{
public:
//Function to return the minimum cost of connecting the ropes.
long long minCost(long long arr[], long long n) {
// MinHeap:
priority_queue<long long, vector<long long>, greater<long long>> pq;
long long cost = 0;
for(long long i = 0; i < n; ++i) {
pq.push(arr[i]);
}
while(pq.size() > 1) {
long long first = pq.top();
pq.pop();
long long second = pq.top();
pq.pop();
cost += (first + second);
pq.push((first+second));
}
return cost;
}
};
//{ Driver Code Starts.
long long 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