Description
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.
Input
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.
Output
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.
Sample Input
6 3
1734251 54 62 2Sample Output
6
30Source
输出区间最大最小值之差,RMQ
#includeusing namespace std;const int N=80005;int dmi[N][30],dma[N][30],f[N];int n,q,l,r;void RMQ_init(){ for(int j=1; (1< <=n; j++) for(int i=1; i+j-1<=n; i++) dmi[i][j]=min(dmi[i][j-1],dmi[i+(1<<(j-1))][j-1]),dma[i][j]=max(dma[i][j-1],dma[i+(1<<(j-1))][j-1]);}int RMQ(int l,int r){ int k=f[r-l+1]; return max(dma[l][k],dma[r-(1< <
线段树
#includeusing namespace std;#define lson l,mi,rt<<1#define rson mi+1,r,rt<<1|1struct T{ int ma,mi,l,r;}tree[200000];int h[50005];int ma,mi;void build(int l,int r,int rt){ tree[rt].l=l,tree[rt].r=r; if(l==r) { tree[rt].ma=tree[rt].mi=h[l]; return; } int mi=(l+r)>>1; build(lson); build(rson); tree[rt].ma=max(tree[rt<<1].ma,tree[rt<<1|1].ma); tree[rt].mi=min(tree[rt<<1].mi,tree[rt<<1|1].mi);}void findma(int l,int r,int rt){ if(tree[rt].l==l&&tree[rt].r==r) { if(tree[rt].ma>ma)ma=tree[rt].ma; return; } int mi=(tree[rt].l+tree[rt].r)>>1; if(mi>=r) findma(l,r,rt<<1); else if(mi >1; if(mi>=r) findmi(l,r,rt<<1); else if(mi