单调队列用法整理
双端队列 + pair
pair 类型的变量下可以直接进行比较。
在不同 pair 的比较中,自动把 x.first 当作第一关键字,x.second 当作第二关键字。
1 定义队列
deque <pair <int, int> > q;
2 定义 pair
pair <int, int> nw = make_pair (x, y);
3 前端、后端插入
q.push_back (make_pair (x, y));
q.push_front (make_pair (x, y));
或者:
pair <int, int> nw = make_pair (x, y);
q.push_front (nw);//后端同理
4 前端、后端弹出
q.pop_back ();
q.pop_front ();
5 清空
q.clear ();
6 带有 pair 的访问
x = q.back ().first, id = q.back ().second;
前端同理。
单调队列
代码
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define rint register int
const int maxn = 1e6 + 5;
int n, k;
int a[maxn];
inline int read ()
{
int x = 1, s = 0;
char ch = getchar ();
while (ch < '0' or ch > '9')
{
if (ch == '-') x = -1;
ch = getchar ();
}
while (ch >= '0' and ch <= '9')
s = s * 10 + ch - '0', ch = getchar ();
return s * x;
}
deque <pair <int, int> > q;
inline void minn ()
{
for (rint i (1); i <= n; ++i)
{
while (!q.empty () and q.front ().second + k - 1 < i)
q.pop_front ();
while (!q.empty () and q.back ().first > a[i])
q.pop_back ();
q.push_back (make_pair (a[i], i));
if (i >= k)
printf ("%lld ", q.front ().first);
}
printf ("\n");
}
inline void maxx ()
{
q.clear ();
for (rint i (1); i <= n; ++i)
{
while (!q.empty () and q.front ().second + k - 1 < i)
q.pop_front ();
while (!q.empty () and q.back ().first < a[i])
q.pop_back ();
q.push_back (make_pair (a[i], i));
if (i >= k)
printf ("%lld ", q.front ().first);
}
}
signed main ()
{
n = read (), k = read ();
for (rint i (1); i <= n; ++i) a[i] = read ();
minn (), maxx ();
return 0;
}
当然了,这题指针模拟双端队列也可以的。
—— E n d End End——
CSP2021 RP += INF;

浙公网安备 33010602011771号