-
Notifications
You must be signed in to change notification settings - Fork 105
/
merge_two_max_heaps.CPP
91 lines (79 loc) · 2.21 KB
/
merge_two_max_heaps.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
82
83
84
85
86
87
88
89
90
91
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
void maxHeapify(vector<int> &arr, int n, int idx) {
// Find largest of node and its children
if (idx >= n) return;
int l = 2 * idx + 1;
int r = 2 * idx + 2;
int max;
if (l < n && arr[l] > arr[idx])
max = l;
else
max = idx;
if (r < n && arr[r] > arr[max]) max = r;
// Put maximum value at root and
// recur for the child with the
// maximum value
if (max != idx) {
swap(arr[max], arr[idx]);
maxHeapify(arr, n, max);
}
}
// Builds a max heap of given arr[0..n-1]
void buildMaxHeap(vector<int> &arr, int n) {
// building the heap from first non-leaf
// node by calling max heapify function
for (int i = n / 2 - 1; i >= 0; i--) maxHeapify(arr, n, i);
}
class Solution{
public:
vector<int> mergeHeaps(vector<int> &a, vector<int> &b, int n, int m) {
vector<int> merged(n+m,0);
for (int i = 0; i < n; i++) merged[i] = a[i];
for (int i = 0; i < m; i++) merged[n + i] = b[i];
buildMaxHeap(merged, n + m);
return merged;
}
};
// { Driver Code Starts.
bool isMerged(vector<int> &arr1, vector<int> &arr2, vector<int> &merged){
if (arr1.size() + arr2.size() != merged.size()){
return false;
}
arr1.insert(arr1.end(),arr2.begin(),arr2.end());
sort(arr1.begin(),arr1.end());
vector<int> mergedCopy =merged;
sort(mergedCopy.begin(),mergedCopy.end());
if (arr1 != mergedCopy){
return false;
}
for(int i = 1; i<merged.size(); i++){
if(merged[i] > merged[(i-1)/2])
return false;
}
return true;
}
int main() {
int t;
cin >> t;
while (t--) {
int n, m, i;
cin >> n >> m;
vector<int> a(n,0),b(m,0);
for (i = 0; i < n; i++) {
cin >> a[i];
}
for (i = 0; i < m; i++) {
cin >> b[i];
}
vector<int> merged, copyA = a, copyB = b;
Solution obj;
merged = obj.mergeHeaps(a, b, n, m);
bool flag = isMerged(copyA, copyB, merged);
if(flag == false) cout<<0<<endl;
else cout<<1<<endl;
}
return 0;
}