← 返回题目页

P2032 扫描

标程

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n, k;
    cin >> n >> k;
    vector<int> a(n);
    for (int &x : a) cin >> x;

    // 单调队列:队列里存下标,值从队首到队尾严格递减,队首就是当前窗口的最大值
    deque<int> q;
    for (int i = 0; i < n; i++) {
        // 队首已经滑出窗口
        while (!q.empty() && q.front() <= i - k) q.pop_front();
        // 队尾比新元素小,它永远轮不到当最大值
        while (!q.empty() && a[q.back()] <= a[i]) q.pop_back();
        q.push_back(i);
        if (i >= k - 1) cout << a[q.front()] << "\n";
    }
    return 0;
}

动画演示