-
Notifications
You must be signed in to change notification settings - Fork 0
/
08- Priority Queue Using Min Heap.cpp
106 lines (101 loc) · 2.92 KB
/
08- Priority Queue Using 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
//in the name of God
#include <iostream>
#include <limits>
#define ll long long
using namespace std;
class MinHeap {
private:
ll *list, capacity, size;
void MinHeapify(int i) {
int l = 2 * i + 1;
int r = 2 * i + 2;
int smallest = i;
if (l < size && list[l] < list[i])
smallest = l;
if (r < size && list[r] < list[smallest])
smallest = r;
if (smallest != i) {
swap(list[i], list[smallest]);
MinHeapify(smallest);
}
}
public:
MinHeap(int sz) {
size = 0;
capacity = sz;
list = new ll[sz];
}
ll ExtractMin() {
if (size <= 0)
return INT_MAX;
if (size == 1) {
size = size - 1;
return list[0];
}
ll root = list[0];
list[0] = list[size - 1];
size = size - 1;
MinHeapify(0);
return root;
}
void UpdateKey(int i, int val) {
if (val < list[i]) {
list[i] = val;
while (i != 0 && list[(i - 1) / 2] > list[i]) {
swap(list[i], list[(i - 1) / 2]);
i = (i - 1) / 2;
}
}
else if (val > list[i]) {
list[i] = val;
MinHeapify(i);
}
}
ll GetMin() {
if (!size)
return INT_MIN;
return list[0];
}
void DeleteKey(int i) {
UpdateKey(i, INT_MIN);
ExtractMin();
}
void InsertKey(ll k) {
if (size == capacity) {
cout << "Overflow: Could not insertKey" << endl;
return;
}
size = size + 1;
int i = size - 1;
list[i] = k;
while (i != 0 && list[(i - 1) / 2] > list[i]) {
swap(list[i], list[(i - 1) / 2]);
i = (i - 1) / 2;
}
}
};
class PriorityQueue {
private:
MinHeap *hp;
public:
PriorityQueue(int sz) {
hp = new MinHeap(sz);
}
ll top() {
return hp->GetMin();
}
void remove() {
hp->ExtractMin();
}
void add(ll k) {
hp->InsertKey(k);
}
};
int main() {
PriorityQueue *pq = new PriorityQueue(1000);
pq->add(1), pq->add(5), pq->add(-2);
cout << pq->top() << endl;
pq->remove();
cout << pq->top() << endl;
return 0;
}