您的位置:首页 > 其它

poj 2823 Sliding Window

2016-11-04 20:21 169 查看
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 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

单调队列基础题,刚刚学单调队列,水一题。学习单调队列,大神博客:http://blog.csdn.net/justmeh/article/details/5844650

#include <iostream>
#include<stdio.h>
#define siz 1000005
using namespace std;
int n,k,a[siz],qx[siz],qy[siz],c[siz][2];
int main()
{
int fx,fy,bx,by,jj,kk;
while(scanf("%d %d",&n,&k)!=EOF){
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
qx[1]=qy[1]=1;
fx=fy=bx=by=jj=kk=1;
if(k==1) c[jj++][0]=c[kk++][1]=a[1];
for(int i=2;i<=n;i++)
{
int u;
///----------------------单调队列核心操作:
u=qx[bx];
while(a[u]>a[i]&&fx<=bx){
bx--;
u=qx[bx];
}
qx[++bx]=i;
if(qx[fx]<i-k+1) fx++;//维护窗口
///----------------------
if(i>=k) c[jj++][0]=a[qx[fx]];
}
for(int i=2;i<=n;i++)
{
int u;

u=qy[by];
while(a[u]<a[i]&&fy<=by){
by--;
u=qy[by];
}
qy[++by]=i;
if(qy[fy]<i-k+1) fy++;

if(i>=k) c[kk++][1]=a[qy[fy]];
}
for(int i=1;i<jj-1;i++)
cout<<c[i][0]<<" ";
cout<<c[jj-1][0]<<endl;
for(int i=1;i<kk-1;i++)
cout<<c[i][1]<<" ";
cout<<c[kk-1][1]<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: