单调队列——Poj Sliding Window

来源:互联网 发布:云计算面临的安全问题 编辑:程序博客网 时间:2024/06/05 09:28

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

Description

An array of size n ≤ 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 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 31 3 -1 -3 5 3 6 7

Sample Output

-1 -3 -3 -3 3 33 3 5 5 6 7

题意:

给定含有n个元素的无序序列a[],和一个整数k,要求求出a[]中,从左向右每连续k个元素组成的序列中的最小值(或最大值),这样的值可能有1个或n-k+1个。

思路:

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

代码:

#include <stdio.h>#define MAXN 1000000int 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;}

原创粉丝点击