- BC20280018's blog
单调队列模板
- 2025-9-13 15:44:37 @
单调队列模板
题目描述
有一个长为 的序列 ,以及一个大小为 的窗口。现在这个窗口从左边开始向右滑动,每次滑动一个单位,求出每次滑动后窗口中的最小值和最大值。
例如,对于序列 以及 ,有如下过程:
$$\def\arraystretch{1.2} \begin{array}{|c|c|c|}\hline \textsf{窗口位置} & \textsf{最小值} & \textsf{最大值} \\ \hline \verb![1 3 -1] -3 5 3 6 7 ! & -1 & 3 \\ \hline \verb! 1 [3 -1 -3] 5 3 6 7 ! & -3 & 3 \\ \hline \verb! 1 3 [-1 -3 5] 3 6 7 ! & -3 & 5 \\ \hline \verb! 1 3 -1 [-3 5 3] 6 7 ! & -3 & 5 \\ \hline \verb! 1 3 -1 -3 [5 3 6] 7 ! & 3 & 6 \\ \hline \verb! 1 3 -1 -3 5 [3 6 7]! & 3 & 7 \\ \hline \end{array} $$输入格式
输入一共有两行,第一行有两个正整数 ;
第二行有 个整数,表示序列 。
输出格式
输出共两行,第一行为每次窗口滑动的最小值;
第二行为每次窗口滑动的最大值。
输入输出样例 #1
输入 #1
8 3
1 3 -1 -3 5 3 6 7
输出 #1
-1 -3 -3 -3 3 3
3 3 5 5 6 7
说明/提示
【数据范围】
对于 的数据,;
对于 的数据,,。
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5, inf = 1e18;
int n, m;
int a[N];
int q[N];
int main()
{
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++)
scanf("%d", &a[i]);
int l = 1, r = 0;
for (int i = 1; i <= n; i++)
{
while (l <= r && a[q[r]] >= a[i])
r--;
while (l <= r && q[l] + m <= i)
l++;
q[++r] = i;
if (i >= m)
printf("%d ", a[q[l]]);
}
printf("\n");
l = 1, r = 0;
for (int i = 1; i <= n; i++)
{
while (l <= r && a[q[r]] <= a[i])
r--;
while (l <= r && q[l] + m <= i)
l++;
q[++r] = i;
if (i >= m)
printf("%d ", a[q[l]]);
}
return 0;
}