POJ2823 Sliding Window (单调队列)

模板:熟练到5分钟之内打出

#include<iostream>
#include<queue>
#include<map>
#include<vector>
#include<cstdio>
#include<algorithm>
#include<stack>
#include<cstring>
using namespace std;
typedef long long ll;
const int N=1e6+7;
const int inf=0x3f3f3f3f;
int f[N];
int q[N];
int a[N];
int main(){
    int i;
    int n,k;
    cin>>n>>k;
    for(i=1;i<=n;i++){
        scanf("%d",&a[i]);
    }
    int hh=0;
    int tt=-1;
    for(i=1;i<=n;i++){
        while(hh<=tt&&q[hh]<=i-k)
            hh++;
        while(hh<=tt&&a[q[tt]]>=a[i])
            tt--;
        q[++tt]=i;
        if(i>=k)
            cout<<a[q[hh]]<<" ";
    }
    cout<<endl;
    hh=0;
    tt=-1;
    for(i=1;i<=n;i++){
        while(hh<=tt&&q[hh]<=i-k)
            hh++;
        while(hh<=tt&&a[q[tt]]<=a[i])
            tt--;
        q[++tt]=i;
        if(i>=k)
            cout<<a[q[hh]]<<" ";
    }
    cout<<endl;
    return 0;

}
View Code

 

posted @ 2020-03-11 16:21  朝暮不思  阅读(94)  评论(0编辑  收藏  举报