题面链接:https://vjudge.net/contest/477276#problem/I
题面:
思路:单调队列,我们可以用双指针来模拟队尾入队和队头出队的过程,也可以用STL中的deque来直接实现
另外要注意的就是队列中存的应该是数组的下标,这样在下标超出窗口时才可以直接弹出
具体参考代码实现
AC代码
#include <iostream>
#include <cstdio>
#include <deque>
using namespace std;
const int N = 1e6;
int a[N + 5];
int n, m;
deque <int> q1, q2;
int main(){
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; ++i) scanf("%d", &a[i]);
for(int i = 1; i <= n; ++i){ //min
if(!q1.empty() && q1.front() < i - m + 1) q1.pop_front();
while(!q1.empty() && a[q1.back()] >= a[i]) q1.pop_back();
q1.push_back(i);
if(i >= m) printf("%d ", a[q1.front()]);
}
puts("");
for(int i = 1; i <= n; ++i){
if(!q2.empty() && q2.front() < i - m + 1) q2.pop_front();
while(!q2.empty() && a[q2.back()] <= a[i]) q2.pop_back();
q2.push_back(i);
if(i >= m) printf("%d ", a[q2.front()]);
}
puts("");
//system("pause");
return 0;
}