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
#include<iostream> #include<cstdio> #include<cmath> #include<string> #include<queue> #include<algorithm> #include<stack> #include<cstring> #include<vector> #include<list> #include<set> #include<map> using namespace std; #define ll long long //#define mod 1000000007 #define pi (4*atan(1.0)) const int N=1e5+10,M=1e6+10,inf=1e9+10; int a[N]; int dpi[N][30];//存位置 int dpa[N][30]; int minn(int x,int y) { return a[x]<=a[y]?x:y; } void rmqi(int len) { for(int i=0; i<len; i++) dpi[i][0]=i; for(int j=1; (1<<j)<len; j++) for(int i=0; i+(1<<j)-1<len; i++) dpi[i][j]=minn(dpi[i][j-1],dpi[i+(1<<(j-1))][j-1]); } int queryi(int l,int r) { int x=(int)(log((double)(r-l+1))/log(2.0)); return minn(dpi[l][x],dpi[r-(1<<x)+1][x]); } int maxx(int x,int y) { return a[x]>=a[y]?x:y; } void rmqa(int len) { for(int i=0; i<len; i++) dpa[i][0]=i; for(int j=1; (1<<j)<len; j++) for(int i=0; i+(1<<j)-1<len; i++) dpa[i][j]=maxx(dpa[i][j-1],dpa[i+(1<<(j-1))][j-1]); } int querya(int l,int r) { int x=(int)(log((double)(r-l+1))/log(2.0)); return maxx(dpa[l][x],dpa[r-(1<<x)+1][x]); } int main() { int x,y,q,i,t; while(~scanf("%d%d",&x,&q)) { for(i=0;i<x;i++) scanf("%d",&a[i]); rmqi(x); rmqa(x); while(q--) { int l,r; scanf("%d%d",&l,&r); if(l>r) swap(l,r); printf("%d\n",a[querya(l-1,r-1)]-a[queryi(l-1,r-1)]); } } }