[AcWing 154] 滑动窗口


点击查看代码
#include<iostream>
using namespace std;
const int N = 1e6 + 10;
int a[N], q[N];
int main()
{
int n, k;
scanf("%d %d", &n, &k);
for (int i = 0; i < n; i ++) scanf("%d", &a[i]);
int hh = 0, tt = -1;
for (int i = 0; i < n; i ++) {
if (hh <= tt && q[hh] < i - k + 1) hh ++;
while (hh <= tt && a[q[tt]] >= a[i]) tt --;
q[++ tt] = i;
if (i >= k - 1) printf("%d ", a[q[hh]]);
}
puts("");
hh = 0, tt = -1;
for (int i = 0; i < n; i ++) {
if (hh <= tt && q[hh] < i - k + 1) hh ++;
while (hh <= tt && a[q[tt]] <= a[i]) tt --;
q[++ tt] = i;
if (i >= k - 1) printf("%d ", a[q[hh]]);
}
return 0;
}
- 求最小值和最大值时分别维护一个单调队列,以最小值为例,队头元素是队列的最小值,每当有一个新元素 x 时,将队列中所有比 x 大的元素删去,把 x 插入到队尾,每当窗口移动时,如果队头元素不在队列中,就把队头元素删去;
- 输出时,i >= k - 1 代表第一个窗口;

浙公网安备 33010602011771号