单调队列:是一种特殊的队列结构,主要用于维护滑动窗口内的极值(最大值或最小值),能够在 O(n) 时间内高效解决相关问题。
入队:新元素从队尾入队,移除破坏单调性的队尾元素。
出队:检查队首元素是否超出窗口范围,若超出则弹出。
T1
#include<bits/stdc++.h>
using namespace std;
#define int unsigned long long
int n,k,q[1000010],a[1000010];
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>n>>k;
for(int i=1;i<=n;i++)cin>>a[i];
int l=1,r=0;
for(int i=1;i<=n;i++){
while(l<=r&&a[i]>=a[q[r]]){
r--;//存下标
}
q[++r]=i;
if(i>=k+q[l]){
l++;
}//弹队首
if(i>=k){
cout<<r-l+1<<"\n";
}
}
return 0;
}T2
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=1e6+5,inf=1e18;
int n,m;
int a[N];
int q[N];
signed main(){
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
cin>>n>>m;
for(int i=1;i<=n;i++){
cin>>a[i];
}
int l=1,r=0;
for(int i=1;i<=n;i++){
while(l<=r && a[q[r]]>=a[i]){
r--;
}
while(l<=r && q[l]+m<=i){
l++;
}
q[++r]=i;
if(i>=m){
cout<<a[q[l]]<<" ";
}
}
cout<<"\n";
l=1,r=0;
for(int i=1;i<=n;i++){
while(l<=r && a[q[r]]<=a[i]){
r--;
}
while(l<=r && q[l]+m<=i){
l++;
}
q[++r]=i;
if(i>=m){
cout<<a[q[l]]<<" ";
}
}
return 0;
}