Monotonous Queue (Sliding Window problem)

Source: Internet
Author: User

Description

An array of sizeN≤ 106 is given to you. There is a sliding window of sizeKWhich is moving from the very left of the array to the very right. You can only seeKNumbers in the window. Each time the Sliding Window moves rightwards by one position. Following is an example:
The array is [1 3-1-3 5 3 6 7], andKIs 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 two lines. The first line contains two integersNAndKWhich are the lengths of the array and the sliding window. There areNIntegers in the second line.

Output

There are two lines in the output. The first line gives the minimum values in the window at each position, from left to right, respectively. The second line gives the maximum values.

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

 

Method 1: priority queue

Use priority_queue in STL to solve the problem. Open two priority queues (max and min). The subscript of the element is inserted in the priority queue, and the element values in the queue are prioritized from large to small. After each element is inserted, the elements in the queue that have run out of the window are deleted. The top element of the queue refers to the maximum or minimum element in the window.

Reference http://hi.baidu.com/xiaohanhoho/blog/item/b020b923aac13cfad6cae228.html

/* Priority queue (STL )*/
# Include <iostream>
# Include <vector>
# Include <queue>
# Define maxn1000005
Using namespace STD;
Int s [maxn]; // saves array data
Int Min [maxn], Max [maxn]; // store the minimum and maximum values
Int CNT;
Struct CMP1 // minimum priority queue, struct + heavy-load operator, note the Writing Method
{
Bool operator () (INT S1, int S2)
{
Return s [S1]> S [s2]; // ascending Element
}
};
Struct cmp2 // maximum priority queue
{
Bool operator () (INT S1, int S2)
{
Return s [S1] <s [s2]; // descending element order
}
};
Priority_queue <int, vector <int>, CMP1> qmin; // custom priority queue
Priority_queue <int, vector <int>, cmp2> Qmax;
Int main ()
{
Int N, K, I;
While (scanf ("% d", & N, & K )! = EOF)
{
For (I = 1; I <= N; I ++)
Scanf ("% d", & S [I]);
For (I = 1; I <= K; I ++) // First insert the first K to the queue
{
Qmin. Push (I );
Qmax. Push (I );
}
CNT = 1;
Min [CNT] = s [qmin. Top ()]; // note that the queue memory is the subscript of the original array.
Max [CNT] = s [Qmax. Top ()];
CNT ++;
For (I = k + 1; I <= N; I ++, CNT ++)
{
Qmin. Push (I );
Qmax. Push (I );
While (i-Qmin.top ()> = k) // Delete the number of sessions that have been removed note here understanding: qmin. top () is the subscript of the minimum element. If the difference between I and the minimum value is greater than or equal to K, that is, the minimum element has been deleted, and qmin is used. pop ();
Qmin. Pop ();
Min [CNT] = s [qmin. Top ()];
While (i-Qmax.top ()> = k) // Delete the number of removed sessions
Qmax. Pop ();
Max [CNT] = s [Qmax. Top ()];
}
For (I = 1; I <CNT; I ++)
Printf ("% d", Min [I]);
Printf ("\ n ");
For (I = 1; I <CNT; I ++)
Printf ("% d", Max [I]);
Printf ("\ n ");
}
Return 0;
}

Method 2: monotonous Queue (***)

What is a monotonous queue?

From: http://www.sunhongfeng.com/2011/07/%E5%8D%95%E8%B0%83%E9%98%9F%E5%88%97-poj2823/

A) from the beginning to the end of the team, the elements are progressively decreasing under the metrics we are concerned about (strictly decreasing rather than not increasing). For example, if each query asks the minimum value in the window, the elements in the queue should increase progressively from left to right (discard useless elements). If you ask the maximum value in the window each time, it should decrease, and so on. This is to ensure that only the Header element is required for each query.

B) from the head of the team to the end of the team, the time point corresponding to the element (which is the subscript of this element in Series A in this question) is increasing progressively, but continuous is not required, this is to ensure that the leftmost element always expires first, and when a new element comes, it must be inserted at the end of the team.

A queue that satisfies the preceding two points is a monotonous queue. First, the sequence of the first element must be a monotonous queue.

How can we maintain this monotonous queue? It is nothing more than processing insert and query operations.

For insert, because of the nature of B, the new elements inserted into the queue can be maintained at the end of B) continue to be established. But in order to maintain a), that is, the elements decrease under the metrics we pay attention to. Some elements at the end of the team may be deleted when new elements are inserted from the end of the team. Specifically, find the first element that is greater than (under the indicator of interest) the new element, delete all the elements after it, and insert the new element after it. Because all deleted elements are smaller than new elements and older than new elements, they cannot be the answer in any future queries, so you can safely delete them.

For queries, due to the nature of B, all elements that expire at this time must be concentrated in the queue header. Therefore, you can use the query time to delete all expired elements in the queue header, the element in the queue header is the answer to the query (type A). You can return it.

Since each element enters the team once, the amortization complexity is O (n ).

# Include <iostream>
# Include <fstream>

Using namespace STD;

# Deprecision Max 1000001
Int A [Max]; // store data
Int Q [Max]; // queue
Int P [Max]; // store subscript I in a [I]
Int Min [Max]; // minimum output
Int MAX [Max]; // maximum output
Int N, K;

Void get_min ()
{
Int I;
Int head = 1, tail = 0;
For (I = 0; I <K-1; I ++) // first put the first two
{
While (Head <= tail & Q [tail]> = A [I]) // The number of elements at the end of the team is greater than the number of elements to be inserted.
-- Tail;
Q [++ tail] = A [I];
P [tail] = I;
}

For (; I <n; I ++)
{
While (Head <= tail & Q [tail]> = A [I])
-- Tail;
Q [++ tail] = A [I];
P [tail] = I;
While (P [head] <I-k + 1) // determines whether the number is outdated, that is, whether the window has crossed this number. I counted it from 0.
{
Head ++;
}
Min [I-k + 1] = Q [head];
}
}

Void get_max ()
{
Int I;
Int head = 1, tail = 0;
For (I = 0; I <K-1; I ++)
{
While (Head <= tail & Q [tail] <= A [I]) // The team end element is smaller than the value to be inserted.
-- Tail;
Q [++ tail] = A [I];
P [tail] = I;
}

For (; I <n; I ++)
{

While (Head <= tail & Q [tail] <= A [I]) // The team end element is smaller than the value to be inserted.
-- Tail;
Q [++ tail] = A [I];
P [tail] = I;
While (P [head] <I-k + 1)
{
Head ++;
}
Max [I-k + 1] = Q [head];
}
}

Void output ()
{
Int I;
// Output the lowest value
For (I = 0; I <n-k + 1; I ++)
{
If (I = 0)
Printf ("% d", Min [I]);
Else
Printf ("% d", Min [I]);
}
Printf ("\ n ");
// Maximum output value
For (I = 0; I <n-k + 1; I ++)
{
If (I = 0)
Printf ("% d", Max [I]);
Else
Printf ("% d", Max [I]);
}
Printf ("\ n ");
}


Int main ()
{
Int I;
Freopen ("acm.txt", "r", stdin );
Scanf ("% d", & N, & K );
For (I = 0; I <n; I ++)
{
Scanf ("% d", & A [I]);
}
Get_min ();
Get_max ();
Output ();
Return 0;
}

Method 3: Line Segment tree (to be continued)

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.