id=3264
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
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
Sample Input
6 3 1 7 3 4 2 5 1 5 4 6 2 2
Sample Output
6 3 0
Source
PS:
百度百科RMQ:http://baike.baidu.com/view/1536346.htm?fr=aladdin
RMQ:http://blog.csdn.net/zztant/article/details/8535764
代码例如以下:
#include <cstdio> #include <cstring> #include <cmath> #include <iostream> using namespace std; const int MAXN = 100117; int n,query; int num[MAXN]; int F_Min[MAXN][20],F_Max[MAXN][20]; void Init() { for(int i = 1; i <= n; i++) { F_Min[i][0] = F_Max[i][0] = num[i]; } for(int i = 1; (1<<i) <= n; i++) //按区间长度递增顺序递推 { for(int j = 1; j+(1<<i)-1 <= n; j++) //区间起点 { F_Max[j][i] = max(F_Max[j][i-1],F_Max[j+(1<<(i-1))][i-1]); F_Min[j][i] = min(F_Min[j][i-1],F_Min[j+(1<<(i-1))][i-1]); } } } int Query_max(int l,int r) { int k = (int)(log(double(r-l+1))/log((double)2)); return max(F_Max[l][k], F_Max[r-(1<<k)+1][k]); } int Query_min(int l,int r) { int k = (int)(log(double(r-l+1))/log((double)2)); return min(F_Min[l][k], F_Min[r-(1<<k)+1][k]); } int main() { int a,b; scanf("%d %d",&n,&query); for(int i = 1; i <= n; i++) scanf("%d",&num[i]); Init(); while(query--) { scanf("%d %d",&a,&b); //printf("区间%d到%d的最大值为:%d ",a,b,Query_max(a,b)); //printf("区间%d到%d的最小值为:%d ",a,b,Query_min(a,b)); printf("%d ",Query_max(a,b)-Query_min(a,b)); } return 0; }