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

来源:互联网 发布:彩票数据分析预测软件 编辑:程序博客网 时间:2024/05/21 10:38

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

#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;}


原创粉丝点击