排队

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
.
.
.
.
.

分析

线段树
.
.
.
.
.
.

程序:
uses math;
var n,i,q,u,v,sum:longint;
  xt,a,mt:array[1..5000000] of longint;
procedure build(l,r,tie:longint);
var mid:longint;
begin
  if r=l then
  begin
    xt[tie]:=a[r];
    mt[tie]:=a[r];
    exit;
  end;
  mid:=(l+r) div 2;
  build(l,mid,tie*2);
  build(mid+1,r,tie*2+1);
  xt[tie]:=min(xt[tie*2],xt[tie*2+1]);
  mt[tie]:=max(mt[tie*2],mt[tie*2+1]);
end;
function sou(l,r,l1,r1,tie:longint):longint;
var mid,ans:longint;
begin
  if (l>=l1) and (r1>=r) then exit(mt[tie]);
  mid:=(l+r) div 2; ans:=-maxlongint;
  if mid>=l1 then ans:=sou(l,mid,l1,r1,tie*2);
  if mid+1<=r1 then ans:=max(ans,sou(mid+1,r,l1,r1,tie*2+1));
  exit(ans);
end;
function sou1(l,r,l1,r1,tie:longint):longint;
var mid,ans:longint;
begin
  if (l>=l1) and (r1>=r) then exit(xt[tie]);
  mid:=(l+r) div 2; ans:=maxlongint;
  if mid>=l1 then ans:=sou1(l,mid,l1,r1,tie*2);
  if mid+1<=r1 then ans:=min(ans,sou1(mid+1,r,l1,r1,tie*2+1));
  exit(ans);
end;
begin
  readln(n,q);
  for i:=1 to n do readln(a[i]);
  build(1,n,1);
  for i:=1 to q do
  begin
    read(u,v);
    sum:=sou(1,n,u,v,1)-sou1(1,n,u,v,1);
    writeln(sum);
  end;
end.

原文地址:https://www.cnblogs.com/YYC-0304/p/9499954.html