Description:
现在有一堆数字共N个数字(N<=10^6),以及一个大小为k的窗口。现在这个从左边开始向右滑动,每次滑动一个单位,求出每次滑动后窗口中的最大值和最小值。
Analysis:
单调队列,eg.最小:只要队列里有元素,并且尾元素比待处理值大,即表示尾元素已经不可能出场,所以出队。直到尾元素小于待处理值,满足"单调"。
第一篇题解
Code
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int MAX_N = 2000010;
int a[MAX_N],front,back,n,m;
int p[MAX_N],q[MAX_N];
int main()
{
scanf("%d%d",&n,&m);
for(int i = 1;i <= n;++i)
{
scanf("%d",&a[i]);
}
front = 1;
back = 0;
for(int i = 1;i <= n;++i)
{
while(front <= back && q[back] >= a[i]) back--;
back++;
q[back] = a[i];
p[back] = i;
while(p[front] + m <= i) front++;
if(i >= m)printf("%d ",q[front]);
}
printf("
");
memset(q,0,sizeof(q));
front = 1;
back = 0;
for(int i = 1;i <= n;++i)
{
while(front <= back && q[back] <= a[i]) back--;
back++;
q[back] = a[i];
p[back] = i;
while(p[front] + m <= i) front++;
if(i >= m)printf("%d ",q[front]);
}
return 0;
}