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
因为只用查找不用更新,所以可以用RMQ算法。(RMQ算法详解见随笔)
#include<cstdio>
#include<iostream>
#include<cmath>
using namespace std;
int m,n;
int a[100005];
int maxx[100005][25];
int minx[100005][25];int ans1,ans2;
int main()
{
scanf("%d%d",&m,&n);//cin>>m>>n;
for(int i=1;i<=m;i++)
{
scanf("%d",&maxx[i][0]);//cin>>maxx[i][0];
minx[i][0]=maxx[i][0];
}
for(int j=1;j<=20;j++)
for(int i=1;i<=m;i++)
if(i+(1<<j)-1<=m)
{
maxx[i][j]=max(maxx[i][j-1],maxx[i+((1<<j-1))][j-1]);
minx[i][j]=min(minx[i][j-1],minx[i+((1<<j-1))][j-1]);
}
for(int i=1;i<=n;i++)
{
int x,y;
scanf("%d%d",&x,&y);//cin>>x>>y;
int k=(int)(log(y-x+1)/log(2.0));
ans1=max(maxx[x][k],maxx[y-(1<<k)+1][k]);
ans2=min(minx[x][k],minx[y-(1<<k)+1][k]);
cout<<ans1-ans2<<endl;
}
return 0;
}