【POJ 2823】Sliding Window

【题目】

传送门

Description

An array of size n n 1 0 6 10^6 is given to you. There is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers 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], 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 two lines. The first line contains two integers n and k which are the lengths of the array and the sliding window. There are n integers 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


【分析】

题目大意:给出 n n 个数并给出 k k ,求每个区间长度为 k k 的最小值和最大值

这道题显然是可以用线段树ST表啊之类的数据结构做的

不过最近在学单调队列,就写一下单调队列版本吧

我们维护两个单调队列,一个维护最小值,一个维护最大值,每次直接取队首就可以了(队首是最优的)

在遇到以下两种情况时要将元素弹出:

  1. 当区间长度大于 k k 时,这时已不符合条件,要弹出队首
  2. 当当前的最优值比队尾还优时,就弹掉队尾(因为它的值更优,位置也更优)

还有就是这倒题的读入量和输出量比较大,建议加读优和输优(代码中为了简介就没加)


【代码】

#include<queue>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 1000005
using namespace std;
int a[N],Min[N],Max[N];
deque<int>big,small;
int main()
{
	int n,k,i;
	scanf("%d%d",&n,&k);
	for(i=1;i<=n;++i)
	{
		scanf("%d",&a[i]),Max[i]=Min[i]=a[i];
		while(!big.empty()&&i-big.front()>=k)  big.pop_front();
		while(!small.empty()&&i-small.front()>=k)  small.pop_front();
		if(!big.empty())  Max[i]=max(Max[i],a[big.front()]);
		if(!small.empty())  Min[i]=min(Min[i],a[small.front()]);
		while(!big.empty()&&a[i]>a[big.back()])  big.pop_back();
		while(!small.empty()&&a[i]<a[small.back()])  small.pop_back();
		big.push_back(i),small.push_back(i);
	}
	for(i=k;i<=n;++i)  printf("%d ",Min[i]);puts("");
	for(i=k;i<=n;++i)  printf("%d ",Max[i]);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/forever_dreams/article/details/83214268
今日推荐