1699: [usaco Jan] balanced lineup queue time limit: 5 sec memory limit: 64 MB
Submit: 933 solved: 568
[Submit] [Status] Description
Every day, John's n (1 <=n <= 50,000) cows always queue in the same sequence. one day John decided to let some cows play a frisbee game. he is going to find a group of continuous cattle in the pair column for the competition. however, to avoid horizontal disparity, the height of a cow should not be too different. john prepared Q (1 <= q <= 180,000) a possible selection of cattle and the height of all cattle (1 <= height <= 1,000,000 ). he wants to know the height difference between the highest and lowest cattle in each group. note: Input and Output consume most of the running time on the maximum data.
Input
* Row 1: N and Q. * 2nd... n + 1: Row I + 1 is the height of the first ox.
* N + 2 .. N + q + 1 row: two integers, A and B (1 <= A <= B <= N), representing all cows from A to B.
Output
* 1st .. Q row: all the answers to the question (the height difference between the highest and lowest cattle), one row.
Sample input6 3
1
7
3
4
2
5
1 5
4 6
2 2
Sample output6
3
0
Hint Source
Gold
Question: bare rmq... Code:
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)) do11 for i:=1 to n-1<<j+1 do12 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)) do16 for i:=1 to n-1<<j+1 do17 g[i,j]:=max(g[i,j-1],g[i+1<<(j-1),j-1]);18 end;19 begin20 assign(input,‘input.txt‘);assign(output,‘output.txt‘);21 reset(input);rewrite(output);22 readln(n,m);23 for i:=1 to n do readln(a[i]);24 rmq;25 for i:=1 to m do26 begin27 readln(x,y);28 k:=trunc(ln(y-x+1)/ln(2));29 mx:=max(g[x,k],g[y-1<<k+1,k]);30 mi:=min(f[x,k],f[y-1<<k+1,k]);31 writeln(mx-mi);32 end;33 close(input);close(output);34 end.
View code