-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path147_Min_Heap.cpp
71 lines (71 loc) · 1.48 KB
/
147_Min_Heap.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
#include <bits/stdc++.h>
using namespace std;
#include <bits/stdc++.h>
void delete_from_heap(vector<int> &ans, vector<int> &heap)
{
if (heap.size() == 1)
return;
ans.push_back(heap[1]);
heap[1] = heap.back();
heap.pop_back();
if (heap.size() == 1)
return;
int root = 1;
while (root < heap.size())
{
int left = 2 * root;
int right = 2 * root + 1;
int swap_idx = root;
if (left < heap.size() && heap[left] < heap[root])
{
swap_idx = left;
}
if (right < heap.size() && heap[right] < heap[swap_idx])
{
swap_idx = right;
}
if (swap_idx != root)
{
swap(heap[swap_idx], heap[root]);
root = swap_idx;
}
else
return;
}
}
void create_min_heap(int val, vector<int> &heap)
{
heap.push_back(val);
int idx = heap.size() - 1;
while (idx > 1)
{
int par = idx / 2;
if (heap[par] > heap[idx])
{
swap(heap[par], heap[idx]);
idx = par;
}
else
{
return;
}
}
}
vector<int> minHeap(int n, vector<vector<int>> &q)
{
vector<int> heap;
heap.push_back(-1);
vector<int> ans;
for (int i = 0; i < n; i++)
{
if (q[i].size() == 2)
{
create_min_heap(q[i][1], heap);
}
else
{
delete_from_heap(ans, heap);
}
}
return ans;
}