题解【洛谷P1886】滑动窗口 /【模板】单调队列

题面

单调队列模板题。

单调队列可以从队首和队尾出队。

队列中的元素大小具有一定的顺序。

具体可参考这一篇题解

#include 
#define itn int
#define gI gi

using namespace std;

inline int gi()
{
    int f = 1, x = 0; char c = getchar();
    while (c < '0' || c > '9') {if (c == '-') f = -1; c = getchar();}
    while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    return f * x;
}

const int maxn = 1000003;

int n, k, a[maxn], q[maxn], p[maxn];

inline void getmin()
{
    int head = 1, tail = 0;
    for (int i = 1; i <= n; i+=1)
    {
        while (head <= tail && q[tail] >= a[i]) --tail;
        q[++tail] = a[i];
        p[tail] = i;
        while (p[head] <= i - k) ++head;
        if (i >= k) printf("%d ", q[head]);
    }
    puts("");
}

inline void getmax()
{
    int head = 1, tail = 0;
    for (int i = 1; i <= n; i+=1)
    {
        while (head <= tail && q[tail] <= a[i]) --tail;
        q[++tail] = a[i];
        p[tail] = i;
        while (p[head] <= i - k) ++head;
        if (i >= k) printf("%d ", q[head]); 
    }
    puts("");
}

int main()
{
    //freopen(".in", "r", stdin);
    //freopen(".out", "w", stdout);
    n = gi(), k = gi();
    for (int i = 1; i <= n; i+=1) a[i] = gi();
    getmin();
    getmax();
    return 0;
}

你可能感兴趣的:(题解【洛谷P1886】滑动窗口 /【模板】单调队列)