单调队列模板(poj2823)

来源:互联网 发布:什么叫品牌战略 知乎 编辑:程序博客网 时间:2024/06/05 20:01
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 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] 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
poj的经验,不能用bits/stdc++.h的头文件。输入要用scanf不然会超时,取消同步也没有用。注意输出的空格。
讲一下题目吧,就是单调队列,用数组(!!切记)模拟队列,然后每次加入一个点,求最小值的话就是使得队列为递增的,求最大值同理。我们可以用两个数组储存值和标号,不会弄错。
#include<iostream>#include<cstdio>#include<cstdlib>#include<cstring>#define maxn 2000001using namespace std;int n,k;int q[maxn],a[maxn],p[maxn],mi[maxn];void Getmin(){int tail=0,head=1;memset(q,0,sizeof(q));memset(p,0,sizeof(p));memset(mi,0,sizeof(mi));for(int i=1;i<k;i++){while(head<=tail&&q[tail]>=a[i])--tail;q[++tail]=a[i];p[tail]=i;}for(int i=k;i<=n;i++){while(head<=tail&&q[tail]>=a[i])--tail;q[++tail]=a[i];p[tail]=i;while(p[head]<i-k+1) ++head;mi[i-k+1]=q[head];}for(int i=1;i<n-k+1;i++)printf("%d ",mi[i]);printf("%d\n",mi[n-k+1]);}void Getmax(){int tail=0,head=1;memset(q,0,sizeof(q));memset(p,0,sizeof(p));memset(mi,0,sizeof(mi));for(int i=1;i<k;i++){while(head<=tail&&q[tail]<=a[i])--tail;q[++tail]=a[i];p[tail]=i;}for(int i=k;i<=n;i++){while(head<=tail&&q[tail]<=a[i])--tail;q[++tail]=a[i];p[tail]=i;while(p[head]<i-k+1) ++head;mi[i-k+1]=q[head];}for(int i=1;i<n-k+1;i++)printf("%d ",mi[i]);printf("%d\n",mi[n-k+1]);}int main(){scanf("%d%d",&n,&k);for(int i=1;i<=n;i++)scanf("%d",&a[i]);Getmin();Getmax();return 0;}