AcWing 154. 滑动窗口(单调队列)

在这里插入图片描述

思路

  1. 利用单调维护递增或递减的序列,从而在队头得出我们想要的极值。

代码

#include <bits/stdc++.h>
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 = 1; i <= n; i ++) scanf("%d", &a[i]);

    int hh = 0, tt = -1;
    for (int i = 1; i <= n; i ++)
    {
    
    
        if (tt >= hh && i - q[hh] >= k) hh ++;
        while (tt >= hh && a[i] <= a[q[tt]]) tt --;
        q[++ tt] = i;

        if (i >= k) printf("%d ", a[q[hh]]);
    }

    printf("\n");

    hh = 0, tt = -1;
    for (int i = 1; i <= n; i ++)
    {
    
    
        if (tt >= hh && i - q[hh] >= k) hh ++;
        while (tt >= hh && a[i] >= a[q[tt]]) tt --;
        q[++ tt] = i;

        if (i >= k) printf("%d ", a[q[hh]]);
    }



    return 0;
}

おすすめ

転載: blog.csdn.net/qq_34261446/article/details/121488869