[Luogu] P1886 滑动窗口
Luogu P1886 滑动窗口
此题为单调队列入门题。单调队列,可以\(O(n)\)求一段数列中区间极值。记录队列中元素大小与该元素在原数组中的位置。当队首元素超出当前求值区间时,头指针加一;当当前将入队元素大于或小于尾元素时,尾指针减一,直到不符合上一条件时,将当前元素入队。然后要求极值只需输出队首元素即可。
#include <cstdio>
const int MAXN = 1000001;
int n, k;
int a[MAXN], que[MAXN], id[MAXN], head, tail;
int main() {
scanf("%d%d", &n, &k);
for (int i = 1; i <= n; ++i)
scanf("%d", &a[i]);
head = 1; tail = 0;
for (int i = 1; i <= n; ++i) {
while(head <= tail && id[head] <= i - k) head++;
while(head <= tail && que[tail] >= a[i]) tail--;
que[++tail] = a[i]; id[tail] = i;
if(i >= k) printf("%d ", que[head]);
}
printf("\n");
head = 1; tail = 0;
for (int i = 1; i <= n; ++i) {
while(head <= tail && id[head] <= i - k) head++;
while(head <= tail && que[tail] <= a[i]) tail--;
que[++tail] = a[i]; id[tail] = i;
if(i >= k) printf("%d ", que[head]);
}
printf("\n");
return 0;
}