Sliding Window
Time Limit: 12000MS | Memory Limit: 65536K | |
Total Submissions: 65974 | Accepted: 18744 | |
Case Time Limit: 5000MS |
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.
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
Source
POJ Monthly--2006.04.28, Ikki
分析
这道题是一个典型的单调队列例题。我们在这题当中有两个小问题,分别求最大最小。我们不急着一次完成,分两个步骤更为妥当。
我们要做的是维护一个单调队列,若求最大,那么维护一个单调递减的队列,反之亦然。
单调队列在这道题中的简单思路,我们以求最大来距离:
入队一个数,
从后往前删,直到队尾的数大于入队数或队列为空。这里的原理是,当前窗口出现了一个大于之前的数字,那么之后的窗口当中,怎么也不可能再用到那些比它小的数字了,从队尾删。也就是代码13~14行。
我们再从队头找,如果找到的数已经到窗口外面去了,那么就直接删除。这里的原理是,我们维护的这个单调队列是的队列里越靠前的数,越处于数列的前部。道理很简单,我们入队一个数的时候,一定是的它处于队尾。也就是代码17~18行。
最后这个单调队列当中,所有的数都再窗口内,且从大到小排序。输出队头。
程序
1 #include <bits/stdc++.h> 2 using namespace std; 3 int n, k, Q[1000000 + 5], a[1000000 + 5], p[1000000 + 5]; 4 int main() 5 { 6 cin >> n >> k; 7 for (int i = 1; i <= n; i++) 8 cin >> a[i]; 9 int Head = 1; 10 int Tail = 0; 11 for (int i = 1; i <= n; i++) 12 { 13 while(Head <= Tail && Q[Tail] >= a[i]) 14 Tail--; 15 Q[++Tail] = a[i]; 16 p[Tail]=i; 17 while (p[Head] <= i-k) 18 Head++; 19 if(i >= k) 20 cout << Q[Head] << " "; 21 } 22 cout << endl; 23 Head = 1; 24 Tail = 0; 25 for (int i = 1; i <= n; i++) 26 { 27 while (Head <= Tail && Q[Tail] <= a[i]) 28 Tail--; 29 Q[++Tail] = a[i]; 30 p[Tail] = i; 31 while (p[Head] <= i-k) 32 Head++; 33 if(i >= k) 34 cout << Q[Head] << " "; 35 } 36 cout << endl; 37 return 0; 38 }