Balanced Lineup
Time Limit: 5000MS | Memory Limit: 65536K | |
Total Submissions: 36864 | Accepted: 17263 | |
Case Time Limit: 2000MS |
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 1 7 3 4 2 5 1 5 4 6 2 2
Sample Output
6 3 0
1 /* 2 ST表:倍增算法的思想。倍增算法的思想也包含动态规划的思想 3 O(nlogn)预处理出数组 st[i][j] 4 代表从s[i]出发的连续2^j个元素中的最值 5 */ 6 #include <iostream> 7 #include <cstdio> 8 #include <cstring> 9 #include <cmath> 10 #include <algorithm> 11 #include <string> 12 #include <vector> 13 #include <stack> 14 #include <queue> 15 #include <set> 16 #include <map> 17 #include <iomanip> 18 #include <cstdlib> 19 using namespace std; 20 const int INF=0x5fffffff; 21 const double EXP=1e-8; 22 const int MS=50005; 23 int a[MS]; 24 int st[MS][20]; 25 int st2[MS][20]; 26 int prelog2[MS]; 27 int N,Q; 28 29 void st_init() 30 { 31 prelog2[1]=0; 32 for(int i=2;i<MS;i++) 33 { 34 prelog2[i]=prelog2[i-1]; 35 if((1<<(prelog2[i]+1))==i) 36 ++prelog2[i]; 37 } 38 for(int i=N-1;i>=0;i--) 39 { 40 st[i][0]=a[i]; 41 st2[i][0]=a[i]; 42 for(int j=1;(i+(1<<j)-1)<N;j++) 43 { 44 st[i][j]=min(st[i][j-1],st[i+(1<<(j-1))][j-1]); 45 st2[i][j]=max(st2[i][j-1],st2[i+(1<<(j-1))][j-1]); 46 } 47 } 48 } 49 int query_min(int l,int r) 50 { 51 int k=prelog2[r-l+1]; 52 return min(st[l][k],st[r-(1<<k)+1][k]); 53 } 54 55 int query_max(int l,int r) 56 { 57 int k=prelog2[r-l+1]; 58 return max(st2[l][k],st2[r-(1<<k)+1][k]); 59 } 60 61 int main() 62 { 63 int l,r; 64 scanf("%d%d",&N,&Q); 65 for(int i=0;i<N;i++) 66 { 67 scanf("%d",&a[i]); 68 } 69 st_init(); 70 while(Q--) 71 { 72 scanf("%d%d",&l,&r); 73 l--; 74 r--; 75 int max_v=query_max(l,r); 76 int min_v=query_min(l,r); 77 printf("%d\n",max_v-min_v); 78 } 79 return 0; 80 }