-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpriority_queue.cpp
107 lines (102 loc) · 2.04 KB
/
priority_queue.cpp
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
#include <iostream>
#define MAX_N 1000001
using namespace std;
/* Generic priority queue implementation using min-heap
Complexity: O(log N) for push/pop, O(1) for isEmpty/GetMinimum
*/
class QueueFullException : public exception
{
virtual const char *what() const throw()
{
return "\nQueue is full\n";
}
};
class QueueEmptyException : public exception
{
virtual const char *what() const throw()
{
return "\nQueue is empty\n";
}
};
template <class T>
class Priority_Queue
{
private:
T PQ[MAX_N];
int heap_size;
public:
Priority_Queue()
{
heap_size = 0;
}
bool isEmpty()
{
return (heap_size <= 0);
}
T GetMinimum()
{
if (isEmpty())
{
QueueEmptyException e;
throw e;
}
return PQ[1];
}
void push(T x)
{
if (heap_size >= MAX_N)
{
QueueFullException e;
throw e;
}
PQ[++heap_size] = x;
int pos = heap_size;
while (pos > 1 && PQ[pos / 2] > PQ[pos])
{
swap(PQ[pos / 2], PQ[pos]);
pos /= 2;
}
}
void pop()
{
if (isEmpty())
{
QueueEmptyException e;
throw e;
}
int ret, left, right, pos = 1;
swap(PQ[pos], PQ[heap_size--]);
while (pos <= heap_size)
{
ret = pos;
left = pos * 2;
right = pos * 2 + 1;
if (left <= heap_size && PQ[left] < PQ[ret])
ret = left;
if (right <= heap_size && PQ[right] < PQ[ret])
ret = right;
if (ret != pos)
{
swap(PQ[pos], PQ[ret]);
pos = ret;
}
else
break;
}
}
};
int main()
{
Priority_Queue<int> q;
q.push(80);
q.push(-5);
q.push(13);
q.push(0);
while (!q.isEmpty())
{
cout << q.GetMinimum() << " ";
q.pop();
}
cout << "\n";
return 0;
}