Week5: sliding window - Monotone queue

Title content
has a length n of the number of columns and a window of size k, the window can be moved back and forth on the columns. Want to know, from left to right in a sliding window, the window each time the number of the maximum and minimum, respectively What example:
the number of columns is [13-1-35367], where k is equal to 3. The
Here Insert Picture Description
input format
is input 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 to be analyzed.

Output format
output two lines. 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 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

Topic analysis
Obviously, if solved, for each segment violence, once k big up, that time complexity of all God directly.
For this question, we can maintain a monotonous queue, and is used deque deque, this way we can maintain only once every monotonic within a range of.
Maintain this deque, the position of the left end point is regarded as the starting point of this queue, the queue for each time (i.e., window) moves, maintaining monotonicity right, the left boundary point than thrown out, it is possible only scan it again to obtain the minimum value at each interval of.

The maximum value of empathy.

#include <iostream>
#include <vector>
#include <string>
#include <deque>
using namespace std;

int n, k;

struct Point
{
	int num;
	int index;
	Point(int n,int i):num(n),index(i){}
};

deque<Point>minwindow;
deque<Point>maxwindow;
vector<int>minans;
vector<int>maxans;

void insert(Point p)
{
	while (!minwindow.empty() && minwindow.back().num > p.num)  minwindow.pop_back();
	minwindow.push_back(p);

	while (!maxwindow.empty() && maxwindow.back().num < p.num)  maxwindow.pop_back();
	maxwindow.push_back(p);
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);

	cin >> n >> k;

	int temp;
	//初始化
	for (int i = 0; i < k - 1; i++)
	{
		cin >> temp;
		Point t(temp, i);

		insert(t);
	}

	for (int i = k - 1; i < n; i++)
	{
		int index = i - k + 1;//窗口最左边的位置
		cin >> temp;
		Point t(temp, i);

		insert(t);
		//弹出窗口最左边之前的数
		while (minwindow.front().index < index) minwindow.pop_front();
		while (maxwindow.front().index < index) maxwindow.pop_front();

		minans.push_back(minwindow.front().num);
		maxans.push_back(maxwindow.front().num);
	}

	for (int i = 0; i < minans.size(); i++)
	{
		cout << minans[i] << ' ';
	}

	cout << endl;

	for (int i = 0; i < maxans.size(); i++)
	{
		cout << maxans[i] << ' ';
	}
}
Published 21 original articles · won praise 3 · Views 406

Guess you like

Origin blog.csdn.net/qq_44506233/article/details/105105845