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
Source
这个题就是给你n个数,q次查询,问最大值与最小值的差,用RMQ做即可,模板题
#include<iostream>
#include<cmath>
#include<cstdio>
#include<algorithm>
#define exp 1e-8
#define mian main
#define pii pair<int,int>
#define pll pair<ll,ll>
#define ll long long
#define pb push_back
#define PI acos(-1.0)
#define inf 0x3f3f3f3f
#define w(x) while(x--)
#define int_max 2147483647
#define lowbit(x) (x)&(-x)
#define gcd(a,b) __gcd(a,b)
#define pq(x) priority_queue<x>
#define ull unsigned long long
#define sc(x) scanf("%d",&x)
#define scl(x) scanf("%lld",&x)
#define pl(a,n) next_permutation(a,a+n)
#define ios ios::sync_with_stdio(false)
#define met(a,x) memset((a),(x),sizeof((a)))
using namespace std;
const int N=1e5+10;
int n,maxnum[N][25],minnum[N][25];
void rmq(int n)
{
for(int i=1;i<20;i++)
for(int j=1;j+(1 << i)-1<=n;j++) //j代表从j开始分为(j,j+2^(i-1)-1),(j+2^(i-1),j+2^i)这两个区间比较
{
maxnum[j][i]=max(maxnum[j][i-1],maxnum[j+(1<<(i-1))][i-1]); //注意优先级
minnum[j][i]=min(minnum[j][i-1],minnum[j+(1<<(i-1))][i-1]);
}
}
int main()
{
while(~sc(n)){
int q;
sc(q);
for(int i=1;i<=n;i++){
sc(maxnum[i][0]);
minnum[i][0]=maxnum[i][0];
}
int l,r; //查询区间
rmq(n);
while(q--){
scanf("%d%d",&l,&r);
int k=(int)(log(r-l+1.0)/log(2.0));
int maxn=max(maxnum[l][k],maxnum[r-(1<<k)+1][k]);
int minx=min(minnum[l][k],minnum[r-(1<<k)+1][k]);
printf("%d\n",maxn-minx);
}
}
}