单调队列——Poj Sliding Window

Sliding Window
Time Limit: 12000MS Memory Limit: 65536K
Total Submissions: 33379 Accepted: 9924
Case Time Limit: 5000MS

Description

An array of size  n ≤ 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  knumbers 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] 7 36
 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个元素的无序序列a[],和一个整数k,要求求出a[]中,从左向右每连续k个元素组成的序列中的最小值(或最大值),这样的值可能有1个或n-k+1个。

思路:

利用单调队列来求解,需要注意的是,单调队列的最大长度为k。单调队列

代码:

#include <stdio.h>

#define MAXN 1000000

int mq[MAXN+5];		//单调队列,存储元素的索引
int f;				//队首指针
int r;				//队尾指针

int a[MAXN+5];		//数字串
int n;				//数字个数
int k;				//滑动窗口大小

void Push_Asc(int i)	//按升序进队
{
	while (r > f && a[i] < a[mq[r-1]])
	{
		r--;
	}
	mq[r++] = i;
}

void Push_Desc(int i)	//按降序进队
{
	while (r > f && a[i] > a[mq[r-1]])
	{
		r--;
	}
	mq[r++] = i;
}

inline int Front(void)
{
	return mq[f];
}

inline bool IsEmpty(void)
{
	return f == r;
}

inline void Pop(void)
{
	f++;
}

void SlidingWindow(bool ascending)
{
	f = r = 0;	//初始化队列
	void (*Push)(int) = ascending ? Push_Asc : Push_Desc;	//判断单调队列是上升还是下降

	int i;
	for (i = 1; i <= k && i <= n; i++)	//让前k个数进队,k有可能大于n
	{
		Push(i);
	}
	printf("%d", a[Front()]);

	for (; i <= n; i++)
	{
		while (!IsEmpty() && Front() + k <= i)	//弹出不在滑动窗口内的元素
		{
			Pop();
		}
		Push(i);
		printf(" %d", a[Front()]);
	}
	putchar('\n');
}

int main(void)
{
	while (scanf("%d%d", &n, &k) != EOF)
	{
		int i;
		for (i = 1; i <= n; i++)
		{
			scanf("%d", &a[i]);
		}

		SlidingWindow(true);
		SlidingWindow(false);
	}
	return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

庞老板

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值