Title Description : http://poj.org/problem?id=2823
Ideas:
To find the maximum and minimum values for an interval, you can use two monotone queues, consider using a double-ended queue because you need to delete elements before the queue and add elements after the queue;
In the double-ended queue to record the subscript of the element, in addition, the double-ended queue is classified as monotone, satisfies the monotone non-increment or monotone non-decrement, the first element of the queue is the interval maximum or the smallest element;
This allows you to find the maximum and minimum values in the interval. The algorithm is linear time and the time complexity is O (N).
Code:
#include <iostream>#include<deque>#defineMax_n (100000 + 10)using namespacestd;intA[max_n];d eque<int>D (max_n);voidMaxofsliding (intNintk);voidMinofsliding (intNintk);intMain () {intN, K; while(SCANF ("%d%d", &n, &k)! =EOF) { for(inti =0; I < n; ++i) scanf ("%d", &A[i]); Minofsliding (n, k); Maxofsliding (n, k); } return 0;}voidMaxofsliding (intNintk) { inti; for(i =0; I < K-1; ++i) {if( ! D.empty () && a[i] >D.back ()) D.pop_back (); D.push_back (i); } for(i = k-1; I < n; ++i) { while( ! D.empty () && I-d.front () >=k) D.pop_front (); while( ! D.empty () && a[i] >D.back ()) D.pop_back (); D.push_back (i); printf ("%d", A[d.front ()]); } d.clear (); printf ("\ n" );}voidMinofsliding (intNintk) { inti; for(i =0; I < K-1; ++i) {if( ! D.empty () && A[i] <D.back ()) D.pop_back (); D.push_back (i); } for(i = k-1; I < n; ++i) { while( ! D.empty () && I-d.front () >=k) D.pop_front (); while( ! D.empty () && A[i] <D.back ()) D.pop_back (); D.push_back (i); printf ("%d", A[d.front ()]); } d.clear (); printf ("\ n" );}
Poj 2823 Sliding Window