题目大意:给出一个数列,给定一个区间大小k,求从左到右每k个数字中的最小值和最大值
分析:单调队列。
所谓单调队列,就是队列有单调性啦~
因此,以求最小值为例,要想一个数入队的话,这个数就要比队尾元素大。那么队头元素一定是最小的,当队头元素的下标等于当前区间的左端点时,就可以出队了。
代码:
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn = 1000010;
int n, k;
int a[maxn];
int m[maxn];
int q[maxn];
int main() {
while(~scanf("%d%d", &n, &k)) {
for(int i = 0; i < n; i++)
scanf("%d", &a[i]);
int s = 0, t = 0;
for(int i = 0; i < n; i++) {
while(s < t && a[q[t-1]] >= a[i]) t--;
q[t++] = i;
if(i-k+1 >= 0) {
m[i-k+1] = a[q[s]];
if(i-k+1 == q[s])
s++;
}
}
for(int i = 0; i <= n-k; i++)
printf("%d%c", m[i], i == n-k ? '\n' : ' ');
s = 0, t = 0;
for(int i = 0; i < n; i++) {
while(s < t && a[q[t-1]] <= a[i]) t--;
q[t++] = i;
if(i-k+1 >= 0) {
m[i-k+1] = a[q[s]];
if(i-k+1 == q[s])
s++;
}
}
for(int i = 0; i <= n-k; i++)
printf("%d%c", m[i], i == n-k ? '\n' : ' ');
}
return 0;
}