# BZOJ1699: [Usaco2007 Jan]Balanced Lineup排队

## 1699: [Usaco2007 Jan]Balanced Lineup排队

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

## 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行: 所有询问的回答 (最高和最低的牛的身高差), 每行一个.

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

6
3
0

## Source

 1 uses math;
2 var i,n,m,k,mx,mi,x,y:longint;
3     f,g:array[0..60000,0..20] of longint;
4     a:array[0..60000] of longint;
5 procedure rmq;
6  var i,j:longint;
7  begin
8  fillchar(f,sizeof(f),60);
9  for i:=1 to n do f[i,0]:=a[i];
10  for j:=1 to trunc(ln(n)/ln(2)) do
11   for i:=1 to n-1<<j+1 do
12    f[i,j]:=min(f[i,j-1],f[i+1<<(j-1),j-1]);
13  fillchar(g,sizeof(g),0);
14  for i:=1 to n do g[i,0]:=a[i];
15  for j:=1 to trunc(ln(n)/ln(2)) do
16   for i:=1 to n-1<<j+1 do
17    g[i,j]:=max(g[i,j-1],g[i+1<<(j-1),j-1]);
18  end;
19 begin
20   assign(input,'input.txt');assign(output,'output.txt');
21   reset(input);rewrite(output);
23   for i:=1 to n do readln(a[i]);
24   rmq;
25   for i:=1 to m do
26     begin
34 end.