洛谷 2880 平衡的陣容 (RMQ)

P2880 [USACO07JAN]平衡的陣容Balanced Lineup

題目描述

For the daily milking, Farmer John’s N cows (1 ≤ N ≤ 50,000) always line up in the same order. One day Farmer John decides to organize a game of Ultimate Frisbee with some of the cows. To keep things simple, he will take a contiguous range of cows from the milking lineup to play the game. However, for all the cows to have fun they should not differ too much in height.

Farmer John has made a list of Q (1 ≤ Q ≤ 200,000) potential groups of cows and their heights (1 ≤ height ≤ 1,000,000). For each group, he wants your help to determine the difference in height between the shortest and the tallest cow in the group.

一個農夫有N頭牛,每頭牛的高度不同,我們需要找出最高的牛和最低的牛的高度差。

輸入輸出格式

輸入格式:
Line 1: Two space-separated integers, N and Q.

Lines 2..N+1: Line i+1 contains a single integer that is the height of cow i

Lines N+2..N+Q+1: Two integers A and B (1 ≤ A ≤ B ≤ N), representing the range of cows from A to B inclusive.

輸出格式:
Lines 1..Q: Each line contains a single integer that is a response to a reply and indicates the difference in height between the tallest and shortest cow in the range.

輸入輸出樣例

輸入樣例#1:
6 3
1
7
3
4
2
5
1 5
4 6
2 2
輸出樣例#1:
6
3
0

很明顯的一道倍增RMQ,注意一下端點的問題就可以了

代碼如下

program mys;

var i,j,k,m,mi,ma,n,t,x1,y1,q:longint;
a:array[0..100000]of longint;
two:array[0..20]of longint;
f,g:array[0..150000,0..16]of longint;

function min(a,b:longint):longint;
begin 
if a<b then exit(a)
else exit(b);
end;

function max(a,b:longint):longint;
begin 
if a>b then exit(a)
else exit(b);
end;

begin 
readln(n,q);
fillchar(g,sizeof(g),$7f);
for i:=1 to n do 
begin 
readln(a[i]);
f[i,0]:=a[i];
g[i,0]:=a[i];
end;

two[0]:=1;
for i:=1 to 20 do 
two[i]:=two[i-1]*2;

for j:=1 to 16 do 
for i:=1 to n do 
begin 
f[i,j]:=max(f[i,j-1],f[i+two[j-1],j-1]);
g[i,j]:=min(g[i,j-1],g[i+two[j-1],j-1]);
end;

for i:=1 to q do 
begin 
readln(x1,y1);
if x1=y1 then 
begin 
writeln(0);
continue;
end;
t:=trunc(ln(y1-x1+1)/ln(2));
mi:=maxlongint;
mi:=min(g[x1,t],g[y1-two[t]+1,t]);
ma:=max(f[x1,t],f[y1-two[t]+1,t]);
writeln(abs(ma-mi));
end;
end.
發佈了33 篇原創文章 · 獲贊 3 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章