BZOJ1699: [Usaco2007 Jan]Balanced Lineup排队

时间:2023-03-09 07:36:02
BZOJ1699: [Usaco2007 Jan]Balanced Lineup排队

1699: [Usaco2007 Jan]Balanced Lineup排队

Time Limit: 5 Sec  Memory Limit: 64 MB
Submit: 933  Solved: 568
[Submit][Status]

Description

每天,农夫 John 的N(1 <= N <= 50,000)头牛总是按同一序列排队. 有一天, John 决定让一些牛们玩一场飞盘比赛. 他准备找一群在对列中为置连续的牛来进行比赛. 但是为了避免水平悬殊,牛的身高不应该相差太大. John 准备了Q (1 <= Q <= 180,000) 个可能的牛的选择和所有牛的身高 (1 <= 身高 <= 1,000,000). 他想知道每一组里面最高和最低的牛的身高差别. 注意: 在最大数据上, 输入和输出将占用大部分运行时间.

Input

* 第一行: N 和 Q. * 第2..N+1行: 第i+1行是第i头牛的身高.

* 第N+2..N+Q+1行: 两个整数, A 和 B (1 <= A <= B <= N), 表示从A到B的所有牛.

Output

*第1..Q行: 所有询问的回答 (最高和最低的牛的身高差), 每行一个.

Sample Input

6 3
1
7
3
4
2
5
1 5
4 6
2 2

Sample Output

6
3
0

HINT

Source

题解:
裸的RMQ。。。
代码:
 uses math;
var i,n,m,k,mx,mi,x,y:longint;
f,g:array[..,..] of longint;
a:array[..] of longint;
procedure rmq;
var i,j:longint;
begin
fillchar(f,sizeof(f),);
for i:= to n do f[i,]:=a[i];
for j:= to trunc(ln(n)/ln()) do
for i:= to n-<<j+ do
f[i,j]:=min(f[i,j-],f[i+<<(j-),j-]);
fillchar(g,sizeof(g),);
for i:= to n do g[i,]:=a[i];
for j:= to trunc(ln(n)/ln()) do
for i:= to n-<<j+ do
g[i,j]:=max(g[i,j-],g[i+<<(j-),j-]);
end;
begin
assign(input,'input.txt');assign(output,'output.txt');
reset(input);rewrite(output);
readln(n,m);
for i:= to n do readln(a[i]);
rmq;
for i:= to m do
begin
readln(x,y);
k:=trunc(ln(y-x+)/ln());
mx:=max(g[x,k],g[y-<<k+,k]);
mi:=min(f[x,k],f[y-<<k+,k]);
writeln(mx-mi);
end;
close(input);close(output);
end.