模板:单调队列

首先给出自己封装好的模板吧。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
template<typename T, unsigned int N, bool (*func)(T, T)>
class MQueue {
private :
pair<T , int >q[N];
int hd, tl, len;
public :
inline void clear(int len) { this->len = len; hd = 0, tl = -1; }
inline int size() { return tl - hd + 1; }
inline bool empty() { return hd > tl; }
inline void push(pair<T, int> ele) {
while(!empty() && (*func)(ele.first, q[tl].first)) tl--;
q[++tl] = ele;
while(!empty() && q[hd].second <= ele.second - len) hd++;
}
inline T front() { return q[hd].first; }
};

代码:模板试用

这题真的没有难度。

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
// #pragma GCC optimize(2)
// #pragma GCC optimize(3, "Ofast", "inline")
#include<bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef __int128 int128;

namespace FastIO
{
// char buf[1 << 20], *p1, *p2;
// #define getchar() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1 << 20, stdin), p1 == p2) ? EOF : *p1++)
template<typename T> inline T read(T& x) {
x = 0;
int f = 1;
char ch;
while (!isdigit(ch = getchar())) if (ch == '-') f = -1;
while (isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar();
x *= f;
return x;
}
template<typename T, typename... Args> inline void read(T& x, Args &...x_) {
read(x);
read(x_...);
return;
}
inline ll read() {
ll x;
read(x);
return x;
}
};
using namespace FastIO;

template<typename T, unsigned int N, bool (*func)(T, T)>
class MQueue {
private :
pair<T , int >q[N];
int hd, tl, len;
public :
inline void clear(int len) { this->len = len; hd = 0, tl = -1; }
inline int size() { return tl - hd + 1; }
inline bool empty() { return hd > tl; }
inline void push(pair<T, int> ele) {
while(!empty() && (*func)(ele.first, q[tl].first)) tl--;
q[++tl] = ele;
while(!empty() && q[hd].second <= ele.second - len) hd++;
}
inline T front() { return q[hd].first; }
};

bool cmp1(int a, int b) { return a < b; }
bool cmp2(int a, int b) { return a > b; }

MQueue<int, 1000010, cmp1>q1;
MQueue<int, 1000010, cmp2>q2;

int n, m;
int a[1000010];

inline void Input() {
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
}
}

inline void Work() {
q1.clear(m), q2.clear(m);
for(int i = 1; i <= n; i++) {
q1.push(make_pair(a[i], i));
if(i >= m) printf("%d ", q1.front());
}
printf("\n");
for(int i = 1; i <= n; i++) {
q2.push(make_pair(a[i], i));
if(i >= m) printf("%d ", q2.front());
}
}

int main() {
int T = 1;
while(T--) {
Input();
Work();
}
return 0;
}