-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPriorityQueue.h
More file actions
96 lines (70 loc) · 1.65 KB
/
PriorityQueue.h
File metadata and controls
96 lines (70 loc) · 1.65 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
94
95
96
#ifndef PRIORITY_QUEUE_H
#define PRIORITY_QUEUE_H
#include <vector>
#include <unordered_map>
#include <cassert>
#include "Data.h"
//the element of priority queue
struct QueueNode
{
int symbol;
int priority;
QueueNode(int symbol=-1, int priority=INFINITY):
symbol(symbol), priority(priority)
{
}
};
// an indexed priority queue implemented via minHeap
class PriorityQueue
{
public:
PriorityQueue() {}
PriorityQueue(const std::vector<int> &symbols);
void changePriority(const QueueNode &node);
// delete the top node
void pop();
inline bool contain(QueueNode &node);
// if the node exists, return false, otherwise, return true
bool insert(const QueueNode &node);
// get the minimum node
inline QueueNode& top();
int size() const { return minHeap.size(); }
private:
void minHeapfy();
void downwards(int i);
void upwards(int i);
// swap corresponding nodes and indices
inline void swap(int i, int j);
std::vector<QueueNode> minHeap;
// map from symbol to index in minHeap
std::unordered_map<int, int> indices;
};
QueueNode& PriorityQueue::top()
{
assert(size() > 0);
return minHeap[0];
}
bool PriorityQueue::contain(QueueNode &node)
{
if (indices.count(node.symbol) > 0)
{
node.priority = minHeap[indices[node.symbol]].priority;
return true;
}
return false;
}
void PriorityQueue::swap(int i, int j)
{
int symbol1 = minHeap[i].symbol;
int symbol2 = minHeap[j].symbol;
// swap nodes
minHeap[i].symbol = symbol2;
minHeap[j].symbol = symbol1;
int temp = minHeap[i].priority;
minHeap[i].priority = minHeap[j].priority;
minHeap[j].priority = temp;
// swap indices
indices[symbol1] = j;
indices[symbol2] = i;
}
#endif