Detailed--Monotone queue classic sliding window problem

Source: Internet
Author: User

A monotone queue, that is, a monotonous queue. The usage frequency is not high, but in some programs will have the unusual function.

Dynamic Programming • The understanding of a monotone queue is often met with a transfer equation like this in dynamic programming: f[x] = Max or min{g (k) | b[x] <= k < x} + W[x](where b[x] does not fall with x monotonically, i.e. b[1]<=b[2]<=b[3]<=...<=b[n]) (G[k] denotes a function related to K or f[k], w[x] represents a function related to x) How is this equation solved? We note the nature of this: if there are two number J, K, make J <= K, and G (k) <= G (j), then decision J is useless. Because of the monotonic nature of B[x], if J can be a legitimate decision, then K must be a legitimate decision, and K is a better decision than J. Because K is better than J, (note: In this classic model, "excellent" is absolute, and is not related to the state currently being computed), so if the decision in the decision table is sorted by K, then G (k) must not fall. In this case, the decision table is f[x]. This leads us to use a monotone queue to maintain the decision table. For each State f (x), the calculation process is divided into the following steps: 1, team first element out of the team, until the first element of the team in a given range. 2. At this point, the first element of the team is the optimal decision of State F (x), 3, calculates g (x), and inserts it into the tail of the monotone queue while maintaining the monotonic of the queue (continuously out of the queue until the queues are monotonous). Repeat the above steps until all function values have been computed. It is not difficult to see this algorithm averaging time complexity is O (1). The time complexity of solving f (x) is thus reduced from O (n^2) to O (n).

The following from a blog + Self-supplement:

Let's start with the simplest questions:

Given an integer sequence of length N (i), i=0,1,..., N-1 and window length K.

Requirements:

f (i) = Max{a (i-k+1), A (i-k+2),..., A (i)},i = 0,1,..., N-1

Another description of the problem is that a window with a length of K is moved on an integer sequence to find the maximum value of the number contained within the window.

Solution One:

A very intuitive solution, that is, from the beginning of the sequence, put the window up, and then find the first k number of the maximum value, and then the last window to move a unit, continue to find the maximum number of K.

For each F (i) of this method, the k-1 is compared and the complexity is O (n*k).

So is there a faster algorithm?

Solution Two:

We know that the previous algorithm has a place to repeat the comparison, that is, when looking for the current F (i), I in front of the number of k-1 other in the calculation F (i-1) when we compare. So can we save the last result? Of course, the largest number of the first k-1 in I. The answer is yes, it's going to use a monotonically decreasing queue.

A monotonically descending queue is a queue whose head elements are always the largest in the queue, and the values in the queue are in descending order. We can insert an element from the end of the queue and delete the element from both ends of the queue.

1. First look at the Insert element: In order to guarantee the descending of the queue, when we insert the element V, we want to compare the elements of the tail with V, if the element at the end of the team is not greater than V, delete the element at the end of the tail, and then continue to compare the elements of the new tail with the V, until the end of the element is more than V,

2. The deletion of the end of the team has just been said, then when the first element of the team to delete it? Since we only need to save the maximum value of the first k-1 elements of I, when the index or subscript of the first element of the team is less than i-k+1, it means that the element of the first team is meaningless for f (i) because it is no longer in the window. So when the first element of the index[team]<i-k+1, the first element of the team is deleted.

(Supplement: The elements in the queue mainly includes two properties: size-Determine whether it affects f[i] evaluation, timeliness (delete team head use)--array subscript Determines whether it has left the sliding window, not affect the f[i], delete the team tail, is the new queue time > has been in the team element, If the value of the team tail is not as good as the value of the newly enqueued element, then the end of the team can be deleted. )

From the above introduction, we know that the only difference between a monotone queue and a queue is that it not only saves the value of the element, but also saves the index of the element (in practice, of course, we can just save the index and indirectly find the value of the current index through the index).

To make the reader understand a little more, let me give you a simple example.

Suppose the sequence is: 8,7,12,5,16,9,17,2,4,6.n=10,k=3.

Then we construct a monotonically descending queue of length 3:

First, the 8 and its index 0 are put into the queue, and we use (8,0) to indicate that the elements in the queue when each step is inserted are as follows:

0: Insert 8, queue for: (8,0)

1: Insert 7, queue for: (8,0), (7,1)

2: Insert 12, queue for: (12,2)

3: Insert 5, queue for: (12,2), (5,3)

4: Insert 16, queue for: (16,4)

5: Insert 9, queue for: (16,4), (9,5)

。。。。 And so on

Then f (i) is the first element in the queue at step I: 8,8,12,12,16,16, ...

Example: POJ 2823 sliding window

Sliding Window
Time Limit: 12000MS Memory Limit: 65536K
Total Submissions: 54158 Accepted: 15543
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
1 #defineN 10000052#include <iostream>3#include <cstring>4 using namespacestd;5#include <cstdio>6 structpai{7     intVal,pos;8 };9 Pai Minque[n],maxque[n];Ten intMinans[n],maxans[n],minhead,maxhead,mintail,maxtail,cur=0; One intn,k; A intMain () - { -scanf"%d%d",&n,&k); the     intnum; -minque[0].val= (1<< to)-1; -maxque[0].val= (1<< to)-1; -maxque[0].val*=-1; + /*use the maximum minimum value, in order to let Que[0] will be occupied by later elements, to prevent because of the que[0]=0 of this number, instead of the original maximum or minimum value, so at first there will be mintail<0, but then immediately ++mintail, no access to the array, So there will be no cross-border situation. */ -      for(intI=1; i<=k;++i) +     { Ascanf"%d",&num); at          while(Minhead<=mintail&&minque[mintail].val>=num) mintail--; -Minque[++mintail].val=num; -minque[mintail].pos=i; -          while(Maxhead<=maxtail&&maxque[maxtail].val<=num) maxtail--; -Maxque[++maxtail].val=num; -maxque[maxtail].pos=i; in     } -      for(inti=k+1; i<=n;++i) to     { +minans[++cur]=Minque[minhead].val; -maxans[cur]=Maxque[maxhead].val; thescanf"%d",&num); *          $          while(minhead<=mintail&&i-minque[minhead].pos>=k) + +Minhead;Panax Notoginseng          while(Minhead<=mintail&&minque[mintail].val>=num) mintail--; -Minque[++mintail].val=num; theminque[mintail].pos=i; +          A          while(maxhead<=maxtail&&i-maxque[maxhead].pos>=k) + +Maxhead; the          while(Maxhead<=maxtail&&maxque[maxtail].val<=num) maxtail--; +Maxque[++maxtail].val=num; -maxque[maxtail].pos=i; $     } $minans[++cur]=Minque[minhead].val; -maxans[cur]=Maxque[maxhead].val; -      for(intI=1; i<=cur;++i) theprintf"%d", Minans[i]); -printf"\ n");Wuyi      for(intI=1; i<=cur;++i) theprintf"%d", Maxans[i]); -     return 0; Wu}

Detailed--Monotone queue classic sliding window problem

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.