1. 程式人生 > >[Luogu] P1886 滑動窗口

[Luogu] P1886 滑動窗口

scanf return AR 入隊 www turn markdown code logs

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; }

[Luogu] P1886 滑動窗口