-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPriorityQueue.cpp
More file actions
93 lines (67 loc) · 1.97 KB
/
Copy pathPriorityQueue.cpp
File metadata and controls
93 lines (67 loc) · 1.97 KB
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
#include <iostream>
#include <vector>
using namespace std;
template<typename Type>
class PriorityQueue{
private:
vector<Type> heap;
int left(const int& index) const {
int answer = index*2 + 1;
return answer>=size() ? -1:answer;
}
int right(const int& index) const {
int answer = index*2 + 2;
return answer>=size() ? -1:answer;
}
int parent(const int& index) const {
return index==0 ? -1 : (index-1)/2;
}
int better_child(const int& current) const {
if(left(current)==-1 && right(current)==-1) return -1;
if(left(current)==-1) return right(current);
if(right(current)==-1) return left(current);
return heap[right(current)] < heap[left(current)] ? left(current):right(current);
}
public:
PriorityQueue() = default;
PriorityQueue(const vector<Type>& v) : PriorityQueue() {
heap.reserve(v.size());
for(const Type& elt : v) this->push(elt);
}
void push(const Type& new_value){
heap.push_back(new_value);
if(size() == 1) return; // queue was emtpy
int p = parent(size()-1);
int current = size()-1;
while(p!=-1 && heap[p] < heap[current]){
swap(heap[current], heap[p]);
current = p;
p = parent(current);
}
}
void pop(){
if(is_empty()) return;
if(size() == 1) return heap.pop_back();
swap(*heap.begin(), *heap.rbegin());
heap.pop_back();
int current = 0;
int c = better_child(current);
while(c!=-1 && heap[current] < heap[c]){
swap(heap[current], heap[c]);
current = c;
c = better_child(current);
}
}
Type top() const {
return *heap.begin();
}
bool is_empty() const {
return heap.begin() == heap.end();
}
int size() const {
return this->heap.size();
}
void clear(){
heap.clear();
}
};