POJ 2823 Sliding Window

题目链接:POJ 2823 Sliding Window

题目大意:
POJ 2823 Sliding Window

题解:
用两个双向队列\(deque\)模拟单调队列来维护区间,一个单调递增,一个单调递减,使当前区间的最大最小值分别出现在两个队列的队首。

#include <cstdio>
#include <deque>
#include <iostream>
using namespace std;

int n, k, a[1000010];

int main() {
    deque<int> maxn, minn;
    scanf("%d%d", &n, &k);
    for (int i = 0; i < n; ++i) {
        scanf("%d", &a[i]);
    }
    for (int i = 0; i < k; ++i) {  // 单调队列
        while (!minn.empty() && a[i] < minn.back()) {
            minn.pop_back();
        }
        minn.push_back(a[i]);
        while (!maxn.empty() && a[i] > maxn.back()) {
            maxn.pop_back();
        }
        maxn.push_back(a[i]);
    }
    // 窗口移动求最小
    for (int i = k; i < n; ++i) {
        cout << minn.front() << " ";
        if (minn.front() == a[i - k]) {
            minn.pop_front();
        }
        while (!minn.empty() && a[i] < minn.back()) {
            minn.pop_back();
        }
        minn.push_back(a[i]);
    }
    cout << minn.front() << " ";
    cout << endl;
    // 窗口移动求最大
    for (int i = k; i < n; ++i) {
        cout << maxn.front() << " ";
        if (maxn.front() == a[i - k]) {
            maxn.pop_front();
        }
        while (!maxn.empty() && a[i] > maxn.back()) {
            maxn.pop_back();
        }
        maxn.push_back(a[i]);
    }
    cout << maxn.front() << " ";
    cout << endl;
    return 0;
}
上一篇:查询优化器内核剖析第五篇:进一步的了解执行计划


下一篇:从环境设置到内存分析:Python代码优化指南