Time Limit: 5000 MS Memory Limit: 0 KB
64-bit integer IO format: %I64d , %I64u Java class name: Main
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.
6 3 1 7 3 4 2 5 1 5 4 6 2 2
6 3 0
1 #include<stdio.h> 2 #include<stdio.h> 3 #include<math.h> 4 #define N 1500001 5 #include<iostream> 6 using namespace std; 7 int maxsum[N][20],minsum[N][20]; 8 void RMQ(int num) 9 { 10 for(int j=1; j<20; j++) 11 { 12 for(int i=1; i<=num; i++) 13 { 14 if(i+(1<<(j-1))<=num) 15 { 16 maxsum[i][j]=max(maxsum[i][j-1],maxsum[i+(1<<(j-1))][j-1]);//这里要加()在1前面,坑了我好久啊 17 minsum[i][j]=min(minsum[i][j-1],minsum[i+(1<<(j-1))][j-1]); 18 // printf("%d %d\n",maxsum[i][j],minsum[i][j]); 19 } 20 } 21 } 22 } 23 int main() 24 { 25 int num,t,query; 26 while(~scanf("%d%d",&num,&query)) 27 { 28 29 for(int i=1; i<=num; i++) 30 { 31 scanf("%d",&maxsum[i][0]); 32 minsum[i][0]=maxsum[i][0]; 33 } 34 RMQ(num); 35 int st,en,maxl,minl; 36 while(query--) 37 { 38 scanf("%d%d",&st,&en); 39 int k=(int)((log(en-st+1))/log(2.0)); 40 maxl=max(maxsum[st][k],maxsum[en-(1<<k)+1][k]); 41 minl=min(minsum[st][k],minsum[en-(1<<k)+1][k]); 42 printf("%d\n",maxl-minl); 43 } 44 } 45 }
之前发过这道题,然而忘加代码了,sorry.
原文:http://www.cnblogs.com/VectorLin/p/5268289.html