单调队列

洛谷P1886滑动窗口

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring> 
#define maxn 1000010
using namespace std;
template<typename T>
inline void read(T &x){
    x=0;bool flag=0;char c=getchar();
    for(;!isdigit(c);c=getchar()) if(c=='-') flag=1;
    for(;isdigit(c);c=getchar()) x=x*10+(c^48);
    if(flag) x=-x;
}

int n,k,a[maxn];
int h,t,q[maxn];

void work1(){//min
    h=1,t=0;
    for(int i=1;i<=n;i++){
        while(h<=t&&q[h]<=i-k) h++;
        while(h<=t&&a[q[t]]>=a[i]) t--;
        q[++t]=i;
        if(i>=k) cout<<a[q[h]]<<" ";
    }
}

void work2(){//max
    h=1,t=0;
    for(int i=1;i<=n;i++){
        while(h<=t&&q[h]<=i-k) h++;
        while(h<=t&&a[q[t]]<=a[i]) t--;
        q[++t]=i;
        if(i>=k) cout<<a[q[h]]<<" ";
    }
}

int main(){
    read(n),read(k);
    for(int i=1;i<=n;i++) read(a[i]);
    memset(q,0,sizeof(q));
    work1();cout<<endl;
    memset(q,0,sizeof(q));
    work2();cout<<endl;
    return 0;
}

 

posted @ 2021-02-17 22:49  DReamLion  阅读(25)  评论(0编辑  收藏  举报