iliya785

rmq.segment_tree

May 21st, 2012
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Pascal 0.89 KB | None | 0 0
  1. const
  2.     inf = maxlongint;
  3. var
  4.     a,t:array[1..100000] of longint;
  5.     i,j,n,m,l,r:longint;
  6.  
  7. function max(a,b:longint):longint;
  8.  begin
  9.    if a>b then
  10.       max:=a
  11.    else
  12.    max:=b;
  13.  end;
  14.  
  15. procedure build;
  16. var i:longint;
  17.  begin
  18.    for i:=n+1 to n shl 1 do
  19.       t[i]:=a[i-n];
  20.    for i:=n downto 1 do
  21.      t[i]:=max(t[i shl 1],t[(i shl 1) + 1]);
  22.  end;
  23.  
  24. function rmq(l,r:longint):longint;
  25. var res:longint;
  26.   begin
  27.     inc(l,n);
  28.     inc(r,n);
  29.     res:=-inf;
  30.     while (l<=r) do
  31.       begin
  32.         if (l and 1 = 1) then
  33.            res:=max(res,t[l]);
  34.         if (r and 1 = 0) then
  35.            res:=max(res,t[r]);
  36.         l:=(l+1) shr 1;
  37.         r:=(r-1) shr 1;
  38.     end;
  39.    rmq:=res;
  40.  end;
  41.  
  42. Begin
  43.   read(n);
  44.   for i:=1 to n do
  45.     read(a[i]);
  46.   build;
  47.   read(m);
  48.   for i:=1 to m do
  49.     begin
  50.      read(l,r);
  51.      writeln(rmq(l,r));
  52.     end;
  53. end.
Advertisement
Add Comment
Please, Sign In to add comment