Sliding Window
Time Limit: 12000MS | | Memory Limit: 65536K |
Total Submissions: 54929 | | Accepted: 15814 |
Case Time Limit: 5000MS |
Description
An array of size n ≤ 10
6 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
用数组模拟单调递减队列deq1,单调递增队列deq2,deq1中的首元素是最大值,deq2中的首元素是最小值,再取队首元素时判断对首元素是否在k个元素的区间内
如果不是则队首指针+1
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <stack>
#include <deque>
#define INF 1e9
#define maxn 1000005
using namespace std;
typedef long long ll;
int num[maxn], maxs[maxn], mins[maxn];
int deq1[maxn], deq2[maxn];
int main(){
// freopen("in.txt", "r", stdin);
int n, k;
while(scanf("%d%d", &n, &k) == 2){
int l1 = 0, r1 = 0, l2 = 0, r2 = 0;
if(k <= 0)
continue;
for(int i = 0; i < n; i++)
scanf("%d", num+i);
for(int i = 0; i < n; i++){
while(l1 != r1 && num[deq1[r1-1]] <= num[i])
r1--;
deq1[r1++] = i;
while(l2 != r2 && num[deq2[r2-1]] >= num[i])
r2--;
deq2[r2++] = i;
if(i >= k-1){
int j = i - k;
while(deq1[l1] <= j)
l1++;
while(deq2[l2] <= j)
l2++;
maxs[i] = num[deq1[l1]];
mins[i] = num[deq2[l2]];
}
}
printf("%d", mins[k-1]);
for(int i = k; i < n; i++)
printf(" %d", mins[i]);
puts("");
printf("%d", maxs[k-1]);
for(int i = k; i < n; i++)
printf(" %d", maxs[i]);
puts("");
}
return 0;
}