题目描述
For the daily milking, Farmer John’s N cows (1 ≤ N ≤ 100,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 ≤ 30) 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.
示例1
输入
6 3
1
7
3
4
2
5
1 5
4 6
2 2
输出
6
3
0
思路解析
题目要求求区间内最大高度减最小高度的值是多少,所以我们需要先构建一个有最大最小值的线段树,然后每次分别查询这个线段树的最大值和最小值,然后两个一减就是答案。
代码
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define ll long long
const int maxn=4e6+10;
const int inf=0x3f3f3f3f;
ll n,m,ma[maxn],mi[maxn],a[maxn];
void pushup(int k){
ma[k]=max(ma[k<<1],ma[k<<1|1]);
mi[k]=min(mi[k<<1],mi[k<<1|1]);
return ;
}
void build(ll l,ll r,ll k){
if(l==r){
mi[k]=ma[k]=a[l];
return ;
}
ll mid=(l+r)>>1;
build(l,mid,k<<1);
build(mid+1,r,k<<1|1);
pushup(k);
return ;
}
ll query_ma(ll l,ll r,ll l1,ll r1,ll k){
if(l==l1&&r==r1){
return ma[k];
}
ll res=0,mid=(l+r)>>1;
if(r1<=mid) res=max(res,query_ma(l,mid,l1,r1,k<<1));
else if(l1>mid) res=max(res,query_ma(mid+1,r,l1,r1,k<<1|1));
else{
res=max(res,query_ma(l,mid,l1,mid,k<<1));
res=max(res,query_ma(mid+1,r,mid+1,r1,k<<1|1));
}
return res;
}
ll query_mi(ll l,ll r,ll l1,ll r1,ll k){
if(l==l1&&r==r1){
return mi[k];
}
ll res=0x3f3f3f3f,mid=(l+r)>>1;
if(r1<=mid) res=min(res,query_mi(l,mid,l1,r1,k<<1));
else if(l1>mid) res=min(res,query_mi(mid+1,r,l1,r1,k<<1|1));
else{
res=min(res,query_mi(l,mid,l1,mid,k<<1));
res=min(res,query_mi(mid+1,r,mid+1,r1,k<<1|1));
}
return res;
}
int main(){
int i,j,k;
scanf("%lld%lld",&n,&m);
for(i=1;i<=n;i++){
scanf("%lld",&a[i]);
}
build(1,n,1);
ll x,y;
while(m--){
scanf("%lld%lld",&x,&y);
ll ans=query_ma(1,n,x,y,1)-query_mi(1,n,x,y,1);
printf("%lld\n",ans);
}
return 0;
}