Time Limit: 5000MS | Memory Limit: 65536K | |
Total Submissions: 45243 | Accepted: 21240 | |
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
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
分析 既可以用线段树也可以用ST来做
1 #include<iostream> 2 #include<cstdio> 3 #include<cmath> 4 #define maxx 50005 5 using namespace std; 6 int maxsum[maxx][18],minsum[maxx][18],n,Q; 7 int _max(int a,int b) 8 { 9 return a>b?a:b; 10 } 11 int _min(int a,int b) 12 { 13 return a<b?a:b; 14 } 15 int main() 16 { 17 18 while(~scanf("%d %d\n",&n,&Q)) 19 { 20 for(int i=1;i<=n;i++) 21 { 22 scanf("%d\n",&maxsum[i][0]); 23 minsum[i][0]=maxsum[i][0]; 24 } 25 for(int j=1;j<=18;j++)// 预处理 26 for(int i=1;i<=n;i++) //j 循环在 i 循环外 27 { 28 if(i+(1<<j)-1<=n) // 注意左右区间 29 { 30 maxsum[i][j]=_max(maxsum[i][j-1],maxsum[i+(1<<(j-1))][j-1]); 31 minsum[i][j]=_min(minsum[i][j-1],minsum[i+(1<<(j-1))][j-1]); 32 } 33 } 34 while(Q--) 35 {int a,b; 36 scanf("%d %d\n",&a,&b); 37 int k=(int)((log((double)(b-a+1)))/log(2.0)); //注意要包含端点并转换成double 38 int maxl=_max(maxsum[a][k],maxsum[b-(1<<k)+1][k]);//不然有些测试要出问题 比如poj 39 int minl=_min(minsum[a][k],minsum[b-(1<<k)+1][k]); 40 printf("%d\n",maxl-minl); 41 } 42 } 43 return 0; 44 }