您的位置:首页 > 其它

[Poj 2823] Sliding Window

2015-06-25 14:38 274 查看

Sliding Window

Time Limit: 12000MS Memory Limit: 65536K

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

题解

单调队列的基本应用

每次从队列头看队列头元素是否在范围中

从队尾向前找到比要加入的点大/小的点,将该点加入队列,去掉后面的

每次答案为队列头

var
ans1,ans2,minn,maxn,x:array[0..1000000]of longint;
head1,tail1,head2,tail2:longint;
i,j:longint;
n,k:longint;
begin
randomize;
head1:=1; head2:=1;
readln(n,k);
for i:=1 to n do
read(x[i]);
for i:=1 to n do
begin
while (head1<=tail1)and(minn[head1]<=i-k) do
inc(head1);
while (head2<=tail2)and(maxn[head2]<=i-k) do
inc(head2);
while (head1<=tail1)and(x[i]<x[minn[tail1]]) do
dec(tail1);
minn[tail1+1]:=i; inc(tail1);
while (head2<=tail2)and(x[i]>x[maxn[tail2]]) do
dec(tail2);
maxn[tail2+1]:=i; inc(tail2);
ans1[i]:=x[minn[head1]];
ans2[i]:=x[maxn[head2]];
end;
for i:=k to n-1 do
write(ans1[i],' ');
writeln(ans1
);
for i:=k to n-1 do
write(ans2[i],' ');
writeln(ans2
);
end.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: