POJ 2823 Sliding Window【单调队列】

Description

An array of sizen≤ 106is given to you. There is a sliding window of sizekwhich is moving from the very left of the array to the very right. You can only see theknumbers 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], andkis 3.
Window positionMinimum valueMaximum 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 integersnandkwhich are the lengths of the array and the sliding window. There arenintegers 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

单调队列2

code:

View Code
#include<stdio.h>
#include<string.h>
int n,m;
int a[1000001];
int q[1000001];
void min_q()
{
int p=0,h=1,k;
q[1]=1;
for(k=1;k<=n;k++)
{
if(k-q[h]==m)
h++;
if(p==h-1||a[k]>a[q[p]])
{
p++;
q[p]=k;
}
else
{
while(p>=h&&a[k]<=a[q[p]])
{
q[p]=k;
p--;
}
p++;
}
if(k>=m)
printf("%d ",a[q[h]]);
}
putchar('\n');
}
void max_q()
{
int p=0,h=1,k;
q[1]=1;
for(k=1;k<=n;k++)
{
if(k-q[h]==m)
h++;
if(p==h-1||a[k]<a[q[p]])
{
p++;
q[p]=k;
}
else
{
while(p>=h&&a[k]>=a[q[p]])
{
q[p]=k;
p--;
}
p++;
}
if(k>=m)
printf("%d ",a[q[h]]);
}
putchar('\n');
}
int main()
{
int i;
scanf("%d%d",&n,&m);
memset(a,0,sizeof(a));
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
min_q();
max_q();
return 0;
}

 

posted @ 2012-03-14 17:43  'wind  阅读(203)  评论(0编辑  收藏  举报