Sliding Window
Time Limit: 12000MS |
|
Memory Limit: 65536K |
Total Submissions: 54931 |
|
Accepted: 15815 |
Case Time Limit: 5000MS |
Description
An array of size
N≤106 is given to you. There is a sliding window of size
kWhich is moving from the very left of the array to the very right. can only see the
kNumbers in the window. Each of the sliding window moves rightwards by one position. Following is an example:
The array is[1 3-1-3 5 3 6 7], and
kis 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 the lines. The first line contains integers
Nand
kWhich is the lengths of the array and the sliding window. There is
NIntegers in the second line.
Output
There is lines in the output. The first line gives the minimum values in the windows at each position, from left to right, respectively. The second line gives the maximum values.
Sample Input
8 31 3-1-3 5 3 6 7
Sample Output
-1-3-3-3 3 33 3 5 5 6 7
Source
POJ monthly--2006.04.28, Ikki parsing: Monotone queue. Note the compiler chooses C + + (C + + ac,g++ TLE)
#include <cstdio> #include <utility>using namespace std;const int maxn = 1e6+5;int N, k;int A[MAXN];p air<in T, int> Q[maxn];int RES_MIN[MAXN], res_max[maxn];void get_min () {int L = 0, r = 0; int i; for (i = 0; i < k-1; ++i) {while (L < R && A[i] <= q[r-1].first)--r; Q[r].first = A[i]; Q[r++].second = i; } int cnt = 0; for (; i < n; ++i) {while (L < R && A[i] <= q[r-1].first)--r; Q[r].first = A[i]; Q[r++].second = i; while (Q[l].second < i-k+1) ++l; res_min[cnt++] = Q[l].first; } for (i = 0; i < cnt-1; ++i) printf ("%d", res_min[i]); printf ("%d\n", Res_min[cnt-1]);} void Get_max () {int L = 0, r = 0; int i; for (i = 0; i < k-1; ++i) {while (L < R && A[i] >= q[r-1].first)--r; Q[r].first = A[i]; Q[r++].second = i; } int cnt = 0; for (; i < n; ++i) { while (L < R && A[i] >= q[r-1].first)--r; Q[r].first = A[i]; Q[r++].second = i; while (Q[l].second < i-k+1) ++l; res_max[cnt++] = Q[l].first; } for (i = 0; i < cnt-1; ++i) printf ("%d", res_max[i]); printf ("%d\n", Res_max[cnt-1]);} void Solve () {get_min (); Get_max ();} int main () {scanf ("%d%d", &n, &k); for (int i = 0; i < n; ++i) scanf ("%d", &a[i]); Solve (); return 0;}
POJ 2823 Sliding Window