-
Notifications
You must be signed in to change notification settings - Fork 0
/
MutablePriorityQueue.h
115 lines (100 loc) · 2.17 KB
/
MutablePriorityQueue.h
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
107
108
109
110
111
112
113
114
115
/*
* MutablePriorityQueue.h
* A simple implementation of mutable priority queues, required by Dijkstra algorithm.
*
* Created on: 17/03/2018
* Author: João Pascoal Faria
*/
#ifndef SRC_MUTABLEPRIORITYQUEUE_H_
#define SRC_MUTABLEPRIORITYQUEUE_H_
#include <vector>
/**
* class T must have: (i) accessible field int queueIndex; (ii) operator< defined.
*/
template <class T>
class MutablePriorityQueue
{
std::vector<T *> H;
void heapifyUp(unsigned i);
void heapifyDown(unsigned i);
inline void set(unsigned i, T *x);
public:
MutablePriorityQueue();
void insert(T *x);
T *extractMin();
void decreaseKey(T *x);
bool empty();
};
// Index calculations
#define parent(i) ((i) / 2)
#define leftChild(i) ((i)*2)
template <class T>
MutablePriorityQueue<T>::MutablePriorityQueue()
{
H.push_back(nullptr);
// indices will be used starting in 1
// to facilitate parent/child calculations
}
template <class T>
bool MutablePriorityQueue<T>::empty()
{
return H.size() == 1;
}
template <class T>
T *MutablePriorityQueue<T>::extractMin()
{
auto x = H[1];
H[1] = H.back();
H.pop_back();
if (H.size() > 1)
heapifyDown(1);
x->queueIndex = 0;
return x;
}
template <class T>
void MutablePriorityQueue<T>::insert(T *x)
{
H.push_back(x);
heapifyUp(H.size() - 1);
}
template <class T>
void MutablePriorityQueue<T>::decreaseKey(T *x)
{
heapifyUp(x->queueIndex);
}
template <class T>
void MutablePriorityQueue<T>::heapifyUp(unsigned i)
{
auto x = H[i];
while (i > 1 && *x < *H[parent(i)])
{
set(i, H[parent(i)]);
i = parent(i);
}
set(i, x);
}
template <class T>
void MutablePriorityQueue<T>::heapifyDown(unsigned i)
{
auto x = H[i];
while (true)
{
unsigned k = leftChild(i);
if (k >= H.size())
break;
if (k + 1 < H.size() && *H[k + 1] < *H[k])
++k; // right child of i
if (!(*H[k] < *x))
break;
set(i, H[k]);
i = k;
}
set(i, x);
}
template <class T>
void MutablePriorityQueue<T>::set(unsigned i, T *x)
{
H[i] = x;
x->queueIndex = i;
}
#endif /* SRC_MUTABLEPRIORITYQUEUE_H_ */