题目
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.
输入
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.
输出
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.
样例输入
6 3
1
7
3
4
2
5
1 5
4 6
2 2
样例输出
6
3
0
思路
简单模板题,只需要动态维护两个区间,一个最大值,一个最小值即可,最后查询输出,因为没有任何的更新操作,所以只需要建树和查询函数即可。
#include<iostream>
#include<cstdio>
using namespace std;
const int maxn=50050;
int maxt[maxn<<2],mint[maxn<<2];
int A[maxn];
void build(int id,int l,int r){
if(l==r){
maxt[id]=A[l];
mint[id]=A[l];
return;
}
int mid=(l+r)>>1;
build(id<<1,l,mid);
build(id<<1|1,mid+1,r);
maxt[id]=max(maxt[id<<1],maxt[id<<1|1]);
mint[id]=min(mint[id<<1],mint[id<<1|1]);
}
int querymax(int id,int l,int r,int a,int b){
if(a<=l&&r<=b){
return maxt[id];
}
int mid=(l+r)>>1;
int ans=0;
if(a<=mid)ans=querymax(id<<1,l,mid,a,b);
if(b>mid)ans=max(ans,querymax(id<<1|1,mid+1,r,a,b));
return ans;
}
int querymin(int id,int l,int r,int a,int b){
if(a<=l&&r<=b){
return mint[id];
}
int mid=(l+r)>>1;
int ans=0x33ffff;
if(a<=mid)ans=querymin(id<<1,l,mid,a,b);
if(b>mid)ans=min(ans,querymin(id<<1|1,mid+1,r,a,b));
return ans;
}
int main(){
int N,Q;
scanf("%d%d",&N,&Q);
for(int i=1;i<=N;i++){
scanf("%d",&A[i]);
}
build(1,1,N);
int x,y;
for(int i=1;i<=Q;i++){
scanf("%d%d",&x,&y);
cout << querymax(1,1,N,x,y)-querymin(1,1,N,x,y)<<endl;
}
return 0;
}