"Problem description"
Give you an array of length n, a sliding form of K is moved from the leftmost to the far right, you can only see the number of K in the window, each time the form is moved to the right, such as the following table:
"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
"Problem-solving ideas"
first, it is not difficult to think of the enumeration method, for each interval, the enumeration of the maximum and minimum values, but for n<=1000000 data, the enumeration must time out, so we can use the queue to optimize.
We take the maximum and the minimum of the first k number, put in two queues, set the maximum value of K, put the minimum value of Q, for each subsequent number if more than the team tail element in K, then K of the team tail elements can be deleted (because it can be proved that in any subsequent interval is not used in the element), if less than the tail element , they joined the queue. The Q queue is an inverse operation. So, for the minimum and maximum of each interval, we only need to record the first element in the Q and K queues. Because of the requirements of the output I used two procedures here, the minimum value first, and then the maximum value. See the code.
"Code Implementation"
varQ,a:Array[1..1000000] ofLongint; N,k,i,j:longint;procedureWork ;varI,f,r:longint;beginF:=1; R:=1; Q[f]:=1; fori:=2 toK Do begin while(F<=R) and(A[q[r]]>=a[i]) DoDec (r); Inc (R); Q[R]:=i; End;//Initialize Q queue write (A[q[f]],' '); fori:=2 ton-k+1 Do begin ifQ[f]<i ThenInc (F); while(F<=R) and(a[q[r]]>=a[i+k-1]) Do//Delete the tail element Dec (r) If the current element is smaller than the team tail element; Inc (R); Q[R]:=i+k-1; Write (A[q[f]],' '); End;End;procedureWork1;varI,f,r:longint;beginF:=1; R:=1; Q[f]:=1; fori:=2 toK Do begin while(F<=R) and(A[q[r]]<=a[i]) DoDec (r); Inc (R); Q[R]:=i; End; write (a[q[f]),' ');//Initialize K queue fori:=2 ton-k+1 Do begin ifQ[f]<i ThenInc (F); while(F<=R) and(a[q[r]]<=a[i+k-1]) Do//If the current number is larger than the tail element, delete the team tail element Dec (r); Inc (R); Q[R]:=i+k-1; Write (A[q[f]],' '); End;End;beginreadln (n,k); fori:=1 toN Doread (a[i]); Fillchar (q,sizeof (q),0); Writeln; Work1; Writeln;End.
Sliding windows (POJ 2823)