【POJ 2823】Sliding Window

本文介绍了一种使用单调队列解决滑动窗口最值问题的高效算法,通过维护两个单调队列,分别找到每个窗口的最大值和最小值,适用于大规模数据处理。

【题目】

传送门

Description

An array of size n n n 1 0 6 10^6 106 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 positionMinimum valueMaximum value
[1 3 -1] -3 5 3 6 7-13
1 [3 -1 -3] 5 3 6 7-33
1 3 [-1 -3 5] 3 6 7-35
1 3 -1 [-3 5 3] 6 7-35
1 3 -1 -3 [5 3 6] 736
1 3 -1 -3 5 [3 6 7]37

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 n 个数并给出 k k k,求每个区间长度为 k k k 的最小值和最大值

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

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

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

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

  1. 当区间长度大于 k 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;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值