Poj3264, poj
Description during daily milking, John's nheaded ox (1 ≤ n ≤ 50000) is always in a column. One day John decided to play a ultimate frisbee game with his cows. For simplicity, he will select a certain number of cows from the dairy queue to play the game. However, all the cows are very interested in this game. John, a farmer, lists the Q (1 ≤ Q ≤ 200000) and the height of each cow (1 ≤ height ≤ 1000000 ). For each list, he wants you to help him determine the heights of the highest and lowest cows in each list. The first behavior of Input is N (1 ≤ N ≤ 50000) and Q (1 ≤ Q ≤ 200000). From row 2nd to row N + 1, each row has a number, indicates the height of the I-head ox (1 ≤ height ≤ 1000000); from row N + 2 to row N + Q + 1, each line has two integers, A and B (1 ≤ A ≤ B ≤ N), which indicate the range from the number A to the number B. Output is an integer from the first row to the Q row, indicating the height difference between the highest and the lowest cattle from the first ox to the second ox. Sample Input6 3
1
7
3
4
2
5
1 5
4 6
2 2
Sample Output6
3
0
Bare RMQ, maintain the minimum and maximum values of the interval, but pay attention to some details ..
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<cmath> 5 using namespace std; 6 const int MAXN=200001; 7 void read(int & n) 8 { 9 char c='+';int x=0;bool flag=0;10 while(c<'0'||c>'9')11 {c=getchar();if(c=='-')flag=1;}12 while(c>='0'&&c<='9')13 {x=x*10+(c-48);c=getchar();}14 flag==1?n=-x:n=x;15 }16 int n,m;17 int a[MAXN],maxrmq[MAXN][51],minrmq[MAXN][51];18 int qmax(int l,int r)19 {20 int k=0;21 while(l+(1<<(k+1))<=r+1)22 k++;23 return max(maxrmq[l][k],maxrmq[r-(1<<k)+1][k]);24 }25 int qmin(int l,int r)26 {27 int k=0;28 while(l+(1<<(k+1))<=r+1)29 k++;30 return min(minrmq[l][k],minrmq[r-(1<<k)+1][k]);31 }32 int main()33 {34 read(n);read(m);35 for(int i=1;i<=n;i++)36 read(a[i]);37 for(int i=1;i<=n;i++)38 maxrmq[i][0]=minrmq[i][0]=a[i];39 for(int j=1;j<=25;j++)40 {41 for(int i=1;i+(1<<j)<=n+1;i++)42 {43 maxrmq[i][j]=max(maxrmq[i][j-1],maxrmq[i+(1<<(j-1))][j-1]);44 minrmq[i][j]=min(minrmq[i][j-1],minrmq[i+(1<<(j-1))][j-1]);45 } 46 }47 for(int i=1;i<=m;i++)48 {49 int x,y;50 read(x);read(y);51 printf("%d\n",qmax(x,y)-qmin(x,y));52 }53 return 0;54 }