-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPriorityQueue.hpp
More file actions
97 lines (79 loc) · 1.8 KB
/
PriorityQueue.hpp
File metadata and controls
97 lines (79 loc) · 1.8 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
97
#ifndef __DSTARLITE_PRIORITYQUEUE_HPP__
#define __DSTARLITE_PRIORITYQUEUE_HPP__
#include <vector>
#include <utility>
#include <algorithm>
using std::make_heap;
using std::pair;
using std::pop_heap;
using std::push_heap;
using std::vector;
using std::deque;
template<class Tp, class Te> class PriorityQueue
{
public:
pair<Tp, Te> top() const
{
return data.front(); // return {priority, elem} pair
}
Tp topKey() const
{
return data.front().first; // return priority only;
}
int size() const
{
return data.size();
}
bool empty() const
{
return data.empty();
}
pair<Tp, Te> pop()
{
std::pop_heap(data.begin(), data.end(), std::greater<pair<Tp, Te>> {});
pair<Tp, Te> temp = data.back();
data.pop_back();
return temp;
}
void push(const Te &elem, const Tp &priority)
{
data.push_back({priority, elem});
std::push_heap(data.begin(), data.end(), std::greater<pair<Tp, Te>> {});
}
void update(const Te &elem, const Tp &priority)
{
auto &&it = find(elem);
if (it == data.end())
{
push(elem, priority);
return;
}
auto &[p, item] = *it;
if (priority == p)
return;
p = priority; // 优先级不同则更新优先级
std::make_heap(data.begin(), data.end(), std::greater<pair<Tp, Te>> {});
}
void remove(const Te &elem)
{
auto &&it = find(elem);
if (it == data.end())
return;
data.erase(it);
std::make_heap(data.begin(), data.end(), std::greater<pair<Tp, Te>> {});
}
private:
vector<pair<Tp, Te>> data;
typename vector<pair<Tp, Te>>::iterator find(const Te &elem)
{
for (auto it = data.begin(); it != data.end(); it++)
{
if (elem == it->second)
{
return it;
}
}
return data.end();
}
};
#endif /* __DSTARLITE_PRIORITYQUEUE_HPP__ */