Description
An array of size n ≤ 106 is given to you. There is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves rightwards by one position. Following is an example:
The array is [1 3 -1 -3 5 3 6 7], and k is 3.
Window position | Minimum value | Maximum value |
---|---|---|
[1 3 -1] -3 5 3 6 7 | -1 | 3 |
1 [3 -1 -3] 5 3 6 7 | -3 | 3 |
1 3 [-1 -3 5] 3 6 7 | -3 | 5 |
1 3 -1 [-3 5 3] 6 7 | -3 | 5 |
1 3 -1 -3 [5 3 6] 7 | 3 | 6 |
1 3 -1 -3 5 [3 6 7] | 3 | 7 |
Your task is to determine the maximum and minimum values in the sliding window at each position.
Input
The input consists of two lines. The first line contains two integers n and k which are the lengths of the array and the sliding window. There are n integers in the second line.
Output
There are two lines in the output. The first line gives the minimum values in the window at each position, from left to right, respectively. The second line gives the maximum values.
Sample Input
8 3
1 3 -1 -3 5 3 6 7
Sample Output
-1 -3 -3 -3 3 3
3 3 5 5 6 7
题目大意
给你N(N ≤ 10 ^ 6)个数,求每个长度为K(K ≤ N)的区间中 ( [1..k], [2..k + 1],…,[n - k + 1..n])中的最大值与最小值。
分析
这道题比较简单,一般做法是用RMQ或者堆,这里主要讲一下最优做法---单调队列
从左向右依次处理每个区间,对于原数组a中两个a[ i ]和a[ j ](i < j),我们发现如果a[ i ] < a[ j ],那么a[ i ]永远不可能成为区间最大值,也就是说啊a[ i ]就没有价值了,可以直接舍去;而如果a[ i ] > a[ j ],也就是说在当前区间中a[ j ]不是最大值,但在后面的区间中可能成为最大值,所以保留该元素。
初始时,依次把前K个元素加入队列,然后输出队首元素,以后每次加入一个当前元素,处理后输出队首元素就是符合条件的最大值。当队首元素不符合条件(本题中就是队头元素下标小于i - k + 1)时,弹出队头元素。
代码:
#include<bits/stdc++.h>
using namespace std;
int a[1000010], q[1000010], p[1000010];
int Min[1000010], Max[1000010];
int n, k;
void get_min() {
int i = 0;
int head = 1, tail = 0;
for(; i < k - 1; i++) {
while(head <= tail && q[tail] >= a[i]) tail--;
q[++tail] = a[i];
p[tail] = i;
}
for(; i < n; i++) {
while(head <= tail && q[tail] >= a[i]) tail--;
q[++tail] = a[i];
p[tail] = i;
while(p[head] < i - k + 1) head++;
Min[i - k + 1] = q[head];
}
}
void get_max() {
int i = 0;
int head = 1, tail = 0;
for(; i < k - 1; i++) {
while(head <= tail && q[tail] <= a[i]) tail--;
q[++tail] = a[i];
p[tail] = i;
}
for(; i < n; i++) {
while(head <= tail && q[tail] <= a[i]) tail--;
q[++tail] = a[i];
p[tail] = i;
while(p[head] < i - k + 1) head++;
Max[i - k + 1] = q[head];
}
}
int main() {
scanf("%d%d", &n, &k);
for(int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
get_min();
get_max();
for(int i = 0; i < n - k + 1; i++) {
if (i == 0) {
printf("%d", Min[i]);
}
else printf(" %d", Min[i]);
}
puts("");
for(int i = 0; i < n - k + 1; i++) {
if (i == 0) {
printf("%d", Max[i]);
}
else printf(" %d", Max[i]);
}
return 0;
}