浅谈队列:https://www.cnblogs.com/AKMer/p/10314965.html
题目传送门:https://www.luogu.org/problemnew/show/P1886
扫两遍,单调队列维护最值即可。
时间复杂度:(O(n))
空间复杂度:(O(n))
代码如下:
#include <cstdio>
using namespace std;
const int maxn=1e6+5;
int n,k,head,tail;
int a[maxn],list[maxn];
int read() {
int x=0,f=1;char ch=getchar();
for(;ch<'0'||ch>'9';ch=getchar())if(ch=='-')f=-1;
for(;ch>='0'&&ch<='9';ch=getchar())x=x*10+ch-'0';
return x*f;
}
int main() {
n=read(),k=read();
for(int i=1;i<=n;i++)
a[i]=read();
for(int i=1;i<=k;i++) {
while(tail!=head&&a[list[tail-1]]>a[i])tail--;
list[tail++]=i;
}
printf("%d ",a[list[head]]);
for(int i=k+1;i<=n;i++) {
while(tail!=head&&a[list[tail-1]]>a[i])tail--;
list[tail++]=i;
while(tail!=head&&i-list[head]>=k)head++;
printf("%d ",a[list[head]]);
}puts("");head=tail=0;
for(int i=1;i<=k;i++) {
while(tail!=head&&a[list[tail-1]]<a[i])tail--;
list[tail++]=i;
}
printf("%d ",a[list[head]]);
for(int i=k+1;i<=n;i++) {
while(tail!=head&&a[list[tail-1]]<a[i])tail--;
list[tail++]=i;
while(tail!=head&&i-list[head]>=k)head++;
printf("%d ",a[list[head]]);
}
return 0;
}