Cod sursa(job #180120)

Utilizator free2infiltrateNezbeda Harald free2infiltrate Data 16 aprilie 2008 17:43:27
Problema Range minimum query Scor 80
Compilator fpc Status done
Runda Arhiva educationala Marime 1.03 kb
program RMQ;
var a : array [0..100000,0..17] of longint;
    v : array [0..100000] of longint;
    p : array [0..17] of longint;
    lg : array [0..100000] of shortint;
    i,j,n,m,x,y,put : longint;
    f,g : text;
begin
assign(f,'rmq.in');
reset(f);
assign(g,'rmq.out');
rewrite(g);
readln(f,n,m);
for i := 1 to n do
readln(f,v[i]);
p[0] := 1;
lg[1] := 0;
put := 0;
x := 1;

for i := 1 to 100000 do begin
if 2*x<=i then begin
               x := 2*x;
               inc(put);
               p[put] := x;
               end;
lg[i] := put;
end;

p[put+1] := x*2;


for i := n downto 1 do begin
A[i,0] := v[i];
j := 1;
while i+p[j]<=n+1 do begin
if a[i,j-1]<a[i+p[j-1],j-1] then a[i,j] := a[i,j-1]
                            else a[i,j] := a[i+p[j-1],j-1];
j := j+1;
end;
end;

for i := 1 to m do begin
readln(f,x,y);
if a[x,lg[y-x+1]]<a[y-p[lg[y-x+1]]+1,lg[y-x+1]] then writeln(g,a[x,lg[y-x+1]])
                        else writeln(g,a[y-p[lg[y-x+1]]+1,lg[y-x+1]]);
end;

close(f);
close(g);

end.