滑动窗口(单调队列板子)

滑动窗口

#include <bits/stdc++.h>
using namespace std;

const int N = 1e6 + 10;

int n, k;
int a[N], q[N];

signed main(){
    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){
        while(hh <= tt && i - k + 1 > q[hh]) ++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){
        while(hh <= tt && i - k + 1 > q[hh]) ++hh;
        while(hh <= tt && a[q[tt]] <= a[i]) --tt;
        q[++tt] = i;
        if(i >= k-1) printf("%d ", a[q[hh]]);
    }
    return 0;
}
posted @ 2025-04-05 21:43  awei040519  阅读(8)  评论(0)    收藏  举报