POJ 2823 Sliding Window + monotone queue

Source: Internet
Author: User

First, concept Introduction 1. Double-ended queue

A double-ended queue is a linear table that is a special kind of queue that adheres to the FIFO principle. The two-terminal queue supports the following 4 operations:

    • (1) Delete from team first
    • (2) Delete from the end of the team
    • (3) Insert from end of team
    • (4) Querying the value of any element in a linear table
2. Monotone Queue

A monotone queue is a special double-ended queue whose internal elements are monotonic. The maximum and minimum queues are two more commonly used monotone queues, with the inner elements being strictly monotonically decreasing (not non-incrementing) and strictly monotonically incrementing (not non-descending).

Common operations for a monotonic queue are as follows:

    • (1) Insert: If the new element breaks the monotony after it is inserted from the end of the queue, the tail element is deleted until it is no longer disruptive until it is inserted and then inserted into the monotone queue.
    • (2) Get the best (maximum, minimum) value: Access to the first element of the team

The following is an example of a monotonically incrementing queue:

Queue size cannot exceed 3, the queued element is 3,2,8,4,5,7,6,4

3 Team: (3)

3 from the end of the team, 2 team: (2)

8 queue: (2,8)

8 from the end of the team, 4 team: (2,4)

5 queue: (2,4,5)

2 from Team head out team, 7 queue: (4,5,7)

7 from the end of the team, 6 team: (4,5,6)

6 from the end of the team, 5 from the end of the team, 4 from the end of the team, 4 team: (4)

The left side is the team head and the right end is the tail of the team.

Second, the application of monotone queue

1, the maximum value of maintenance:

For example, we want to maintain a monotone queue with a maximum interval of k, because the newly inserted node his "vitality" is certainly longer than the element that was already in the queue "live", the element will be inserted continuously compared to the tail element, if he is larger than the tail element of the team, Then tail--the team tail element is deleted, (because the current inserted element value (set to POS) is larger, and "live" time, there is POS, the tail element of the "life" of the year will never be the maximum value, so directly ignoring the small end of the line than Pos. Until the empty position or find a larger than the point of the end of the queue.

2. Poj 2823 Sliding Window Description

An array of size n ≤106 are given to you. There is a sliding window of size K which was moving from the very left of the array to the very right. You can only see the K numbers 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 K is 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 the integers n and K which is the lengths of the array and the sliding window. There is n integers 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
Ideas First,

This topic has a very important message, that is, all the intervals are equal length and continuous, then for the "adjacent" two intervals (l,r) and (l+1,r+1) Some of the most beautiful properties:   al,al+1,al+2,..., ar-1,ar,ar+1, take the maximum as an example: We notice that in the interval (l,r),Max (al,al+1,al+2, ..., Ar-1,ar)=max (Al,max (al+1,al+2,..., ar-1,ar))

in the interval (l+1,r+1), Max (al+1,al+2,..., ar-1,ar,ar+1) =max (max (al+1,al+2,..., ar-1,ar), ar+1)

The two formulas have the same part max (al+1,al+2,..., Ar-1,ar), and experience tells us that the maximum probability of the interval (l,r) falling in the (L+1,r) interval is very high. Well, when it comes to the l+1,r+1, we don't need to scan again. It is only necessary to rescan when the last maximum has been dropped on AL, so the algorithm has been greatly optimized.

continue to consider such a problem, take the maximum as an example, for any l<=i<=j<=r, if Ai<aj, then, in the process of moving the interval to the right, the maximum value will never fall on the AI, because AI than AJ first failure, can use AI must be able to use AJ, Now we don't need AI anymore. This property coincides with the monotone queue nature. while scanning this sequence, we maintain a monotonically decreasing queue. when we move the interval from (l,r) to (l+1,r+1), the ar+1 is inserted into the monotone queue, and if the first element of the team is not (l+1,r+1), delete it. the first element in this process is the maximum value in the (l+1,r+1) interval.

Second,

Look at this question: An array of size n ≤106 is given to you. There is a sliding window of size K which was moving from the very left of the array to the very right. You can only see the K numbers in the window. Each of the sliding window moves rightwards by one position. Your task is to determine the maximum and minimum values in the sliding window at each position.

That is, there is a sequence a that asks you to ask for the minimum value in Series B and C,b[i] (a[i]...a[i+w-1], c[i] is the maximum value. If A is 1,3,-1,-3,5,3,6,7, then B is -1,-3,-3,-3,3,3,c for 3,3,5,5,6,7.

This problem is equivalent to a stream of data (sequence a) is constantly coming, and the data is constantly expiring, the equivalent of we can only save limited data (sliding window of the data, this problem is the width of the Windows W), for the arrival of the query (the query in this topic is every moment), We want to return the minimum value of the maximum value in the current sliding window. Note that the element is constantly expiring.

To solve this problem, you can use a data structure called a monotone queue that maintains a queue like this:

    • A) from the team head to the end of the team, the elements are decreasing (strictly decreasing, not non-incrementing) under the indicator we are concerned with, for example, if the query is the minimum value within the window, then the elements in the queue should be incremented from left to right, and if the maximum value within the window is queried each time, then the This is to ensure that each query only needs to take the team head element.
    • b) from the head to the end of the team, the element corresponding to the moment (in this case, the element in the sequence a subscript) is incremented, but does not require continuous, this is to ensure that the leftmost element is always the first to expire, and every time a new element comes, it must be inserted at the end of the team.

The queue that satisfies the above two points is the monotone queue, first of all, only the sequence of the first element must be a monotone queue.

So how do you maintain this monotonous queue? It is nothing more than handling inserts and querying two operations.

For insertion, because of the nature of B, the new element that comes in is inserted into the queue and the last can be maintained B) continues to be established. But in order to maintain the establishment of a, that is, the element is decreasing under the index of our concern, it is possible to remove elements from the tail when inserting new elements from the end of the team, specifically, to find the first element that is greater than (under the target of interest) The new element, delete all subsequent elements, and insert the new element behind it. because all the deleted elements are smaller than the new elements and older than the new ones, it is impossible to be an answer in any future queries, so you can safely delete them.

for queries, because of the nature of B, all elements that expire at that time must be focused on the team header, so use the time of the query to delete all expired elements of the team header, without the expiration element, the team header element is the answer to the query (Nature a), return it. The amortization complexity is O (n) because each element is in the queue once.

#include <stdio.h> #include <string.h>const int maxn = 1000005;int A[maxn],q[maxn];int n,k;void Monotonequeue (int op) {    memset (q,0,sizeof (q));    BOOL first = true;    int head = 1,tail = 0;    for (int i = 1, i <= N; i++)    {while        (head <= tail && ((!op && a[i] <= a[q[tail]) | | (Op && a[i] >= A[q[tail])) tail--;        Q[++tail] = i;        while (head <= tail && Q[tail]-q[head] >= k) head++;        if (i >= k) first?printf ("%d", A[q[head]]):p rintf ("%d", A[q[head]]), first = false;    }    printf ("\ n");} int main () {    scanf ("%d%d", &n,&k);    for (int i = 1; I <= n; i++)    {        scanf ("%d", &a[i]);    }    Monotonequeue (0); Maintain monotonically decreasing queue     monotonequeue (1);//Maintain monotonically incrementing queue     return 0;}

#include <iostream> #include <cstdio> #include <cstring> #include <algorithm>using namespace Std;typedef __int64 ll;const int maxn = 1000005;    struct node{int pos,val;} q[maxn];int num[maxn],n,k;int min[maxn];int max[maxn];void getmin () {int head=1,tail=0; for (int i=1; i<k; i++) {///Pre-k-1 number is not related to query, put directly in while (Head<=tail&&num[i]<q[tail].val) Tai        l--;        The Insert preparation operation, either the queue is empty, or a location is found that conforms to the monotone queue definition tail++;        Q[tail].val=num[i];        Q[tail].pos=i;        Insert} for (int i=k, i<=n; i++) {while (head<=tail&&num[i]<q[tail].val) tail--;        tail++;        Q[tail].val=num[i];        Q[tail].pos=i;        while (i-q[head].pos>=k) head++;        Delete operation, maintain the maximum interval length min[i-k]=q[head].val;    Answer record}}void Getmax () {int head=1,tail=0;        for (int i=1, i<k; i++) {while (head<=tail&&num[i]>q[tail].val) tail--;        tail++;        Q[tail].val=num[i]; Q[Tail].pos=i;        } for (int i=k, i<=n; i++) {while (head<=tail&&num[i]>q[tail].val) tail--;        tail++;        Q[tail].val=num[i];        Q[tail].pos=i;        while (i-q[head].pos>=k) head++;    Max[i-k]=q[head].val;        }}int Main () {while (scanf ("%d%d", &n,&k)!=eof) {for (int i=1; i<=n; i++) scanf ("%d", &num[i]);        Getmin (); for (int i=0; i<=n-k; i++) printf ("%d%c", min[i],i==n-k? '        \ n ': ');        Getmax (); for (int i=0; i<=n-k; i++) printf ("%d%c", max[i],i==n-k? '    \ n ': '); } return 0;}

 

POJ 2823 Sliding Window + monotone queue

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.