-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathmonotonic_queue.cpp
65 lines (57 loc) · 1.3 KB
/
monotonic_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
#include <bits/stdc++.h>
using namespace std;
/**
* Monotonic queue to keep track of the minimum and/or the maximum
* elements so far in the queue in O(1).
*/
template<class T>
class monotonic_queue {
queue<T> qu;
deque<T> mx, mn;
public:
/**
* Pushes a new element to the end of this queue.
*
* @param v the new element to be pushed.
*/
void push(T v) {
qu.push(v);
while (mx.size() && mx.back() < v) mx.pop_back();
mx.push_back(v);
while (mn.size() && mn.back() > v) mn.pop_back();
mn.push_back(v);
}
/**
* Pops the front element from the queue.
* If the queue is empty, an exception is thrown.
*/
void pop() {
if (mx.front() == qu.front()) mx.pop_front();
if (mn.front() == qu.front()) mn.pop_front();
qu.pop();
}
/**
* @return the front element of the queue.
*/
T front() const {
return qu.front();
}
/**
* @return the maximum element of the queue.
*/
T max() const {
return mx.front();
}
/**
* @return the minimum element of the queue.
*/
T min() const {
return mn.front();
}
/**
* @return the size of the queue.
*/
size_t size() const {
return qu.size();
}
};