[Programming thinking and practice Week5 job D] sliding window

Subject description:

There are a number of columns of length n, and a window of size k, the window can be moved back and forth on the columns. Now we want to know when the sliding window from left to right, each window the maximum and minimum numbers were number.
For example: the number of columns is [13-1-35367], where k is equal to 3.
Here Insert Picture Description

Enter a description:

Enter two lines. The first line of two integers n and k are the size and length of the sliding window series, 1 <= k <= n <= 1000000. The second row has n represents an integer number of columns.

Sample Input:

8 3
1 3 -1 -3 5 3 6 7

Output Description:

There are two lines of output. The first output line of each sliding window position from left to right, the minimum value in the sliding window. The second line is the maximum.

Sample Output:

-1 -3 -3 -3 3 3
3 3 5 5 6 7

Ideas:

What is required is to take the size of the most value in the sliding window K, a partial concept, we still can be used with the job A stack similar ideas which monotonically, most value monotonically stack can strike the global scope, because here the concept is a partial, therefore, for the elements that do not belong to the current range should be removed, so the team first element due to sliding window to the right and may be removed, it is thought a monotonous queue.
Establish a monotonically increasing queue, each number in turn pushed, pushed to the number does not meet the monotony of the queue, then the tail element removal, until the elements to be pressed into monotone, then pressed into the deal team the first element to inspect whether the current scope (because every time it is only one element pressed into consideration only the first digit of the team), if not part of the current range, it is removed, then the team is the first element in a press the element is the smallest element in the right boundary of the sliding window, until finally pushed a number, this time he obtained a minimum of all windows.
Similarly establish a monotone decreasing the queue, and the maximum value to each window position.

Code:

#include <iostream>
using namespace std;
const int size=1e6+10;
int st[size],val[size];
int Min[size],Max[size];
int l=1,r=0,n,k;
int main(int argc, char** argv) {
	scanf("%d%d",&n,&k);
	for(int i=1;i<=n;i++)
		scanf("%d",val+i);
	for(int i=1;i<=n;i++)
	{
		while(l<=r&&val[st[r]]>val[i]) r--;
		st[++r]=i;
		if(l<=r&&st[r]-st[l]+1>k) l++;
		Min[i]=val[st[l]];
	} 
	l=1;r=0;
	for(int i=1;i<=n;i++)
	{
		while(l<=r&&val[st[r]]<val[i]) r--;
		st[++r]=i;
		if(l<=r&&st[r]-st[l]+1>k) l++;
		Max[i]=val[st[l]];
	} 
	for(int i=k;i<=n;i++)
		printf("%d ",Min[i]);
	printf("\n");
	for(int i=k;i<=n;i++)
		printf("%d ",Max[i]);
	printf("\n");
	return 0;
}
Published 24 original articles · won praise 8 · views 526

Guess you like

Origin blog.csdn.net/weixin_44034698/article/details/104995580