-
Notifications
You must be signed in to change notification settings - Fork 0
/
optimal-merge-pattern.cpp
58 lines (44 loc) · 1.15 KB
/
optimal-merge-pattern.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
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
/*
Consider Problem Statement :
Find the optimal time of merging n sorted lists having a[i] number of elements
for 0 <= i < n. You can only merge two lists at a time.
[Hint] : Greedy Approach
The idea is to merge lists with smallest number of elements.
*/
int findOptimalTime(vector<int> a, int n) {
// since we want two minimums at a time
// create a min heap
priority_queue<int, vector<int>, greater<int>> pq;
// push the sizes to pq
for(int i=0; i<n; i++)
pq.push(a[i]);
int result = 0;
while(pq.size() > 1) {
// pop two smallest from min heap
int first = pq.top();
pq.pop();
int second = pq.top();
pq.pop();
// total time to merge these two
int temp = first + second;
// add it to result
result += temp;
// add the combined list to pq
pq.push(temp);
}
return result;
}
int main() {
int n;
cin>>n;
vector<int> v(n);
for(int i=0; i<n; i++) {
cin>>v[i];
}
int result = findOptimalTime(v, n);
cout<<"Output: "<<result;
}