找长度为k的窗口中的最大值(单调减队列),最小值(单调增队列)
#include<iostream>
using namespace std;
const int N = 1000010;
int n, k;
int a[N];
int q[N], hh = -1, tt = 0;
int main(){
cin >> n >> k;
for(int i = 0; i < n; i ++) cin >> a[i];
for(int i = 0; i < n; i ++){
while(hh <= tt && q[hh] < i - k + 1) hh ++;
while(hh <= tt && a[q[tt]] >= a[i]) tt --;
q[++ tt] = i;
if(i >= k - 1) cout << a[q[hh]] << ' ';
}
hh = 0, tt = -1;
cout << endl;
for(int i = 0; i < n; i ++){
while(hh <= tt && q[hh] < i - k + 1) hh ++;
while(hh <= tt && a[q[tt]] <= a[i]) tt --;
q[++ tt] = i;
if(i >= k - 1) cout << a[q[hh]] << ' ';
}
return 0;
}