4373 窗口
时间限制: 1 s
空间限制: 256000 KB
题目等级 : 黄金 Gold
题解
查看运行结果
题目描述 Description
给你一个长度为N的数组,一个长为K的滑动的窗体从最左移至最右端,你只能见到窗口的K个数,每次窗体向右移动一位,如下表:
Window position Min value
Max 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
你的任务是找出窗口在各位置时的max value, min value.
输入描述 Input Description
第1行n,k,第2行为长度为n的数组
输出描述 Output Description
2行
第1行每个位置的min value
第2行每个位置的max value
样例输入 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
数据范围及提示 Data Size & Hint
数据范围:20%: n<=500; 50%: n<=100000;100%: n<=1000000;
program df;
var i,j,n,m,z,l,r,l1,r1:longint;
a,b1,c1,b2,c2,x,y:array[0..3000000] of longint;
begin
readln(n,m);
for i:=1 to n do
read(a[i]);
l:=1; r:=0;
l1:=1; r1:=0;
for i:=1 to m do //先把前m个元素放入
begin
while (l<=r) and (b1[r]<=a[i]) do dec(r);
inc(r);
b1[r]:=a[i];
c1[r]:=i;
while (l1<=r1) and (b2[r1]>=a[i]) do dec(r1);
inc(r1);
b2[r1]:=a[i];
c2[r1]:=i;
end;
x[m]:=b1[l];
y[m]:=b2[l1];
for i:=m+1 to n do
begin
while (l<=r) and (b1[r]<=a[i]) do dec(r); //保证栈递增
inc(r);
b1[r]:=a[i];
c1[r]:=i;
while (l<=r) and (c1[l]<=i-m) do inc(l); //保证单调栈的区间长度等于M
while (l1<=r1) and (b2[r1]>=a[i]) do dec(r1); //保证栈递减
inc(r1);
b2[r1]:=a[i];
c2[r1]:=i;
while (l1<=r1) and (c2[l1]<=i-m) do inc(l1); //和上面一样
x[i]:=b1[l];
y[i]:=b2[l1];
end;
for i:=m to n do
write(y[i],’ ‘);
writeln;
for i:=m to n do
write(x[i],’ ‘);
end.