Sliding Window
Time Limit: 12000MS |
|
Memory Limit: 65536K |
Total Submissions: 41264 |
|
Accepted: 12229 |
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
I did some optimization simulations according to my own thinking, and still timed out.
Code:
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <algorithm> #include < Deque>using namespace Std;struct node{int mi;int ma;} Q[1000004];int A[1000004];int Main () {int n, k;int i, j;scanf ("%d%d", &n, &k), for (int i=0; i<n; i++) scanf ("%d", &a[i]); int dd=a[0], ff=a[0];for (i=1; i<k; i++) {if (A[I]>DD) dd=a[i];//maxif (A[I]<FF) ff=a[i];//min}int e= 0;Q[E].MA=DD; Q[e++].mi=ff;int pos;for (j=k; j<n; j + +)//traverse these sequences {if (A[J]>DD) dd=a[j];if (A[J]<FF) ff=a[j];//Determine whether to update pos=j-k; if (a[pos]>dd && a[pos]<ff) Continue;else{int p, w;if (A[POS]==DD)//start is = = Max Update max value {p=a[pos+1];for (i=pos+ 2; i<=j; i++) {P=max (P, a[i]);} Dd=p;} else if (A[POS]==FF)//start is = = Minimum update minimum value {w=a[pos+1];for (i=pos+2; i<=j; i++) {w=min (W, a[i]);} Ff=w;} Q[E].MA=DD; Q[E++].MI=FF;}} for (i=0; i<e; i++) {if (i==e-1) printf ("%d\n", Q[I].MI); else printf ("%d", Q[I].MI);} for (i=0; i<e; i++) {if (i==e-1) printf ("%d\n", Q[I].ma]; else printf ("%d", q[i].ma);} return 0;}
POJ 2823 Sliding window (the most-valued problem of sliding windows)