WEEK 5 D sliding window

topic:

ZJM has a sequence of length n and a window of size k. The window can move back and forth on the sequence. Now ZJM wants to know when the window slides from left to right, the maximum and minimum values ​​of the number in the window each time How much. For example:
Insert picture description here

Input

There are two lines of input. The two integers n and k in the first row represent the length of the sequence and the size of the sliding window, 1 <= k <= n <= 1000000. In the second row, there are n integers representing the sequence of ZJM.

Output

The output has two lines. The first line outputs the minimum value of the sliding window at each position from left to right. The second line is the maximum value.

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

Ideas

Here is the maximum value in the sliding window of size k. For i, the maximum and minimum values ​​of the interval [i-k + 1, i] are required. Therefore, for elements that are not in the current range, Removal, that is, the head element, so it is more appropriate to use the queue structure here.
Create a monotonically increasing queue, and press each number in turn. If the number to be pushed does not satisfy the monotonicity of the queue, the element at the end of the queue will be removed until the element to be pushed does not affect the monotonicity. After pressing in, it should be checked whether the head element belongs to the current range, if it does not belong to the current range, it is removed. In the processed queue, the head element is the smallest element in the sliding window with the pushed element as the right boundary, until the last number is pressed, and the minimum value of all windows can be obtained at this time.
Similarly, a monotonically decreasing queue can be established to find the maximum value of each window position.

Code

#include <iostream>

using namespace std;

const int N = 1e7 + 10;
int min0[N], max0[N], q[N],a[N];
int n, k;

void solvemin()
{
	int l = 1, r = 0;
	for (int i = 1; i <= n; i++)
	{
		while (r >= l && a[q[r]] >= a[i])
			r--;
		q[++r] = i;
		if (q[r] - q[l] + 1 > k)
			l++;
		min0[i] = a[q[l]];
	}
}

void solvemax()
{
	int l = 1, r = 0;
	for (int i = 1; i <= n; i++)
	{
		while (r >= l && a[q[r]] <= a[i])
			r--;
		q[++r] = i;
		if (q[r] - q[l] + 1 > k)
			l++;
		max0[i] = a[q[l]];
	}
}

int main()
{
	while (scanf("%d %d",&n,&k)!=EOF)
	{
		for (int i = 1; i <= n; i++)
			scanf("%d", &a[i]);
		solvemin();
		solvemax();
		cout << min0[k];
		for (int i = k + 1; i <= n; i++)
			cout << ' ' << min0[i];
		cout << endl;
		cout << max0[k];
		for (int i = k + 1; i <= n; i++)
			cout << ' ' << max0[i];
		cout << endl;
	}
	return 0;
}

Published 32 original articles · Likes0 · Visits 682

Guess you like

Origin blog.csdn.net/qq_43814559/article/details/105001771