https://www.luogu.org/problemnew/show/P1886

单调队列的操作上比普通队列多了可以从尾端出队

单调队列保持队内元素单调递增/递减,以保证队首元素为最小/最大元素

 

详细解释https://www.luogu.org/problemnew/solution/P1886

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
vector<int> a;
vector<int> q;
int n,k;
void findMin(){
    int head=1,tail=0;
    for(int i=1;i<=n;i++){
        while(head<=tail&&q[head]+k<=i)
            head++;
        while(head<=tail&&a[q[tail]]>a[i])
            tail--;
        q[++tail]=i;
        if(i>=k)
            cout<<a[q[head]]<<' ';
    }
    cout<<endl;
}
void findMax(){
    int head=1,tail=0;
    for(int i=1;i<=n;i++){
        while(head<=tail&&q[head]+k<=i)
            head++;
        while(head<=tail&&a[q[tail]]<a[i])
            tail--;
        q[++tail]=i;
        if(i>=k)
            cout<<a[q[head]]<<' ';
    }
    cout<<endl;
}
int main(){
    cin>>n>>k;
    a.resize(n+1);
    q.resize(n+1);
    for(int i=1;i<=n;i++)
        cin>>a[i];
    findMin();
    findMax();
    return 0;
}