lkb 的小屋

start again. //小蒟蒻也有大梦想

[SMOJ2117]Sliding Window(静态RMQ问题)

单调队列模板题。
参考代码:

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

const int MAXN = 1e6 + 100;

int n, k;
int a[MAXN], ans[2][MAXN];

int q1[MAXN], q2[MAXN];
int l1, r1, l2, r2;

inline int readint() {
    char c = getchar();
    while ((c < '0' || c > '9') && c != '-') c = getchar();
    int num = 0; int neg = 1;
    if (c == '-') { neg = -1; c = getchar(); }
    while (c >= '0' && c <= '9') {
        num = (num << 3) + (num << 1) + (c - '0');
        c = getchar();
    }
    return num * neg;
}

inline void writeint(int x) {
//  printf("%d\n", x); return;
    if (!x) putchar('0');
    else if (x < 0) {
        putchar('-');
        x *= -1;
    }
    static int t[10];
    int i = 0;
    while (x) {
        t[i++] = x % 10;
        x /= 10;
    }
    while (i--) putchar(t[i] + '0');
    putchar(' ');
}

int main(void) {
    freopen("2117.in", "r", stdin);
    freopen("2117.out", "w", stdout);
    n = readint(); k = readint();
    for (int i = 0; i < n; i++) a[i] = readint();

    q1[r1++] = q2[r2++] = 0;
    ans[0][0] = ans[1][0] = a[0];
    for (int i = 1; i < k; i++) {
        ans[0][0] = std::min(ans[0][0], a[i]);
        ans[1][0] = std::max(ans[1][0], a[i]);
        while (r1 - l1 && a[q1[r1 - 1]] >= a[i]) --r1;
        while (r2 - l2 && a[q2[r2 - 1]] <= a[i]) --r2;
        q1[r1++] = q2[r2++] = i;
    }

    for (int i = k; i < n; i++) {
        while (r1 - l1 && i - q1[l1] >= k) ++l1;
        while (r2 - l2 && i - q2[l2] >= k) ++l2;
        while (r1 - l1 && a[q1[r1 - 1]] >= a[i]) --r1;
        while (r2 - l2 && a[q2[r2 - 1]] <= a[i]) --r2;
        q1[r1++] = q2[r2++] = i;
        ans[0][i - k + 1] = a[q1[l1]]; ans[1][i - k + 1] = a[q2[l2]];
    }

    for (int i = 0; i + k <= n; i++) writeint(ans[0][i]); putchar('\n');
    for (int i = 0; i + k <= n; i++) writeint(ans[1][i]);
    return 0;
}


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013686535/article/details/76906313
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

[SMOJ2117]Sliding Window(静态RMQ问题)

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭