用stl双端队列维护的单调队列
- 核心思想:最优性原则
即若队列中的状态没有新状态优(大或小),就将老状态弹出 - 实现方式
手写双端队列
stl双端队列
例题 luogu P1886 滑动窗口
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/1213f2b8e68a9a0880dec2e80ab92e5b.png)
code
#include<bits/stdc++.h>
using namespace std;
#define loop(i,start,end) for(int i=start;i<=end;i++)
#define anti_loop(i,start,end) for(int i=start;i>=end;i--)
#define clean(arry,num); memset(arry,num,sizeof(arry));
#define min(a,b) ((a<b)?a:b)
#define ll long long
const int maxn=1000000+10;
const int maxk=1000000;
int n,k;
struct node{int id;int num;};
deque<node>D;
deque<node>X;
int data[maxn];
int maxx[maxn],minn[maxn];
inline int read()
{
int neg=1;int ans=0;char r=getchar();
while(r>'9'||r<'0'){if(r=='-')neg=-1;r=getchar();}
while(r>='0'&&r<='9'){ans=ans*10+r-'0';r=getchar();}
return ans*neg;
}
int main()
{
n=read();k=read();
loop(i,1,n){data[i]=read();}
loop(i,1,n)
{
while(!D.empty()&&D.front().id<i-k+1)
D.pop_front();
while(!D.empty()&&D.back().num<data[i])
D.pop_back();
node newer;newer.id=i;newer.num=data[i];D.push_back(newer);
if(i>=k)maxx[i-k+1]=D.front().num;
while(!X.empty()&&X.front().id<i-k+1)
X.pop_front();
while(!X.empty()&&X.back().num>data[i])
X.pop_back();
newer;newer.id=i;newer.num=data[i];X.push_back(newer);
if(i>=k)minn[i-k+1]=X.front().num;
}
loop(i,1,n-k+1)printf("%d ",minn[i]);
printf("\n");
loop(i,1,n-k+1)printf("%d ",maxx[i]);
return 0;
}