https://www.jianshu.com/p/0bf8d8f1e450
https://blog.csdn.net/qq_42754826/article/details/89052630
#include<cstdio>
#define N 1000020
using namespace std;
int n,k;
int a[N];
struct monotone_queue{
int q[N],p[N];
int head,tail;
}minq,maxq;
void min_query()
{
minq.head=1;
minq.tail=0;
for(int i=1;i<=n;i++)
{
while(minq.head<=minq.tail&&minq.q[minq.tail]>=a[i]) minq.tail--;
minq.q[++minq.tail]=a[i];
minq.p[minq.tail]=i;
while(minq.head<=minq.tail&&minq.p[minq.head]<=i-k) minq.head++;
if(i>=k)printf("%d ",minq.q[minq.head]);
}
printf("\n");
}
void max_query()
{
maxq.head=1;
maxq.tail=0;
for(int i=1;i<=n;i++)
{
while(maxq.head<=maxq.tail&&maxq.q[maxq.tail]<=a[i]) maxq.tail--;
maxq.q[++maxq.tail]=a[i];
maxq.p[maxq.tail]=i;
while(maxq.head<=maxq.tail&&maxq.p[maxq.head]<=i-k) maxq.head++;
if(i>=k)printf("%d ",maxq.q[maxq.head]);
}
}
int main()
{
scanf("%d %d",&n,&k);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
min_query();
max_query();
return 0;
}
原文地址:https://www.cnblogs.com/little-cute-hjr/p/11625778.html