[Luo Gu 1886] sliding window

A classic monotone queue topics

Original title Portal

It refers to a monotone law element rendered as a monotonic, increasing, decreasing, or custom 1576249-20190816123042323-327652433.png

Refers to a queue can only be operated (so monotonous queue can also be used to achieve the STL deque) and the tail from the head of the queue, the queue only monotonous but ejection head of the queue, the tail of the insertion and ejection


Each subject was required number of k successive maximum and minimum values, to maintain a maximum value, for example, in the range for any, and the number x in the queue, y, a New Force number z, z> x && z> y, then from the tail into the team z, x, y dequeue

Code:

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>

using namespace std;
const int maxn = 1000100;

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

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

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

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

Guess you like

Origin www.cnblogs.com/wyctstf/p/11363161.html
Recommended