forked from RafaelPortacio/notwaze
-
Notifications
You must be signed in to change notification settings - Fork 0
/
priority-queue.hpp
58 lines (48 loc) · 1.56 KB
/
priority-queue.hpp
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
#pragma once
#include <iostream>
#include <vector>
#include "graph.hpp"
template <typename T, typename Compare>
class PriorityQueue {
public:
void priority_queuefy(size_t i) {
size_t l = l_child(i);
size_t r = r_child(i);
size_t smallest = i;
if (l < data.size() && compare(data[l], data[smallest]))
smallest = l;
if (r < data.size() && compare(data[r], data[smallest]))
smallest = r;
if (smallest != i) {
std::swap(data[i], data[smallest]);
priority_queuefy(smallest);
}
}
[[nodiscard]] size_t size() const {
return data.size();
}
[[nodiscard]] T top() const {
assert(!empty());
return data.front();
}
[[nodiscard]] bool empty() const {
return data.empty();
}
void push(const T& k) {
data.push_back(k);
for (size_t i = data.size() - 1; i > 0 && compare(data[i], data[parent(i)]); i = parent(i))
swap(data[i], data[parent(i)]);
}
void pop() {
assert(!empty());
data.front() = data.back();
data.pop_back();
priority_queuefy(0);
}
private:
static size_t parent(size_t i) { return ((i+1) >> 1) - 1; }
static size_t l_child(size_t i) { return ((i+1) << 1) - 1; }
static size_t r_child(size_t i) { return ((i+1) << 1); }
std::vector<T> data;
Compare compare;
};