Skip to content
Author: loop3r
Date: 20251015
tag: 滑动窗口
link: https://www.luogu.com.cn/problem/P1886

题目描述

link

分析

代码实现

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

int main() {
    int n, k; cin >> n >> k;
    
    int a[1000010];
    for (int i = 1; i <= n; i++) cin >> a[i];
    
    deque<int> q;
    for (int i = 1; i <= n; i++) {
        while (q.size() && q.front() < i - k + 1) q.pop_front();
        while (q.size() && a[q.back()] >= a[i]) q.pop_back();
        q.push_back(i);
        if (i >= k) cout << a[q.front()] << " ";
    }
    cout << endl;

    q.clear();
    for (int i = 1; i <= n; i++) {
        while (q.size() && q.front() < i - k + 1) q.pop_front();
        while (q.size() && a[q.back()] <= a[i]) q.pop_back();
        q.push_back(i);
        if (i >= k) cout << a[q.front()] << " ";
    }
    cout << endl;

    return 0;
}