洛谷 2880 平衡的阵容 (RMQ)

来源:互联网 发布:java origin 编辑:程序博客网 时间:2024/04/29 02:32

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.
0 0
原创粉丝点击