题目链接:http://poj.org/problem?id=3264
RMQ裸题
贴代码
var n,Q:longint;
fmax,fmin:array[0..50005,0..20]of longint;
function min(x,y:longint):longint;
begin
if x<y then exit(x) else exit(y);
end;
function max(x,y:longint):longint;
begin
if x>y then exit(x) else exit(y);
end;
procedure init;
var i:longint;
begin
assign(input,'Balanced.in');reset(input);
assign(output,'Balanced.out');rewrite(output);
readln(n,Q);
for i:=1 to n do
begin
readln(fmax[i,0]);
fmin[i,0]:=fmax[i,0];
end;
end;
procedure main;
var L,R,x,y,i,j:longint;
begin
for j:=1 to trunc(ln(n)/ln(2)) do
for i:=1 to n-(1<<j)+1 do
begin
fmax[i,j]:=max(fmax[i,j-1],fmax[i+1<<(j-1),j-1]);
fmin[i,j]:=min(fmin[i,j-1],fmin[i+1<<(j-1),j-1]);
end;
for i:=1 to Q do
begin
readln(L,R);
j:=trunc(ln(R-L+1)/ln(2));
x:=max(fmax[L,j],fmax[R-(1<<j)+1,j]);
y:=min(fmin[L,j],fmin[R-(1<<j)+1,j]);
writeln(x-y);
end;
end;
procedure print;
begin
close(input);close(output);
end;
begin
init;
main;
print;
end.
【写的有漏洞的,欢迎路过大神吐槽】
2016/11/14 14:55:04
Ending.