分析:经典的队列应用,实现N的最大最小查找。

var
  a,q:array[0..1000000] of longint;
  i,j,head,tail,n,m:longint;

begin
  readln(n,m);
  for i:=1 to n do read(a[i]);
  head:=1; tail:=1; q[1]:=1;
  for i:=2 to m-1 do
    begin
      while (head<=tail)and(a[q[tail]]>=a[i]) do dec(tail);
      inc(tail);
      q[tail]:=i;
    end;
  for i:=m to n do
    begin
      while (head<=tail)and(q[head]<=i-m) do inc(head);
      while (head<=tail)and(a[q[tail]]>=a[i]) do dec(tail);
      inc(tail);
      q[tail]:=i;
      write(a[q[head]],' ');
    end;
  writeln;
  head:=1; tail:=1; q[1]:=1;
  for i:=2 to m-1 do
    begin
      while (head<=tail)and(a[q[tail]]<=a[i]) do dec(tail);
      inc(tail);
      q[tail]:=i;
    end;
  for i:=m to n do
    begin
      while (head<=tail)and(q[head]<=i-m) do inc(head);
      while (head<=tail)and(a[q[tail]]<=a[i]) do dec(tail);
      inc(tail);
      q[tail]:=i;
      write(a[q[head]],' ');
    end;
  writeln;
end.

  

相关文章:

  • 2022-12-23
  • 2021-10-21
  • 2021-07-25
  • 2021-10-16
猜你喜欢
  • 2021-12-07
  • 2021-10-27
  • 2021-08-19
  • 2022-02-08
相关资源
相似解决方案