Poj 2823 Sliding Window

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.