第一次写线段树,参考了人家的才会.
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 50100;
const int My_Max = 999999999;
struct Node{
int l,r,Min,Max;
};
int h[maxn];
Node st[maxn<<2];
int nMax,nMin;
void BuildTree(int rt,int l,int r){
st[rt].l = l;
st[rt].r = r;
if(l == r)
st[rt].Max = st[rt].Min = h[l];
else{
int mid = (l + r) >> 1;
BuildTree(rt << 1, l, mid );
BuildTree(rt << 1 | 1, mid +1, r);
st[rt].Max = max(st[rt << 1].Max, st[rt << 1 | 1].Max);
st[rt].Min = min(st[rt << 1].Min, st[rt << 1 | 1].Min);
}
}
void Query(int rt,int l,int r){
if(nMin <= st[rt].Min && nMax >= st[rt].Max)
return ;
int mid = (st[rt].l + st[rt].r) >> 1;
if(l == st[rt].l && r == st[rt].r){
nMax = max( st[rt].Max, nMax);
nMin = min( st[rt].Min, nMin);
}
else if(mid < l)
Query(rt << 1 | 1, l, r);
else if(mid >= r)
Query(rt << 1 , l, r);
else{
Query(rt << 1 | 1, mid + 1, r);
Query(rt << 1 , l, mid);
}
}
int main(){
int n,m;
while(~scanf("%d %d",&n,&m)){
for(int i = 1; i <= n; ++i)
scanf("%d",&h[i]);
BuildTree(1,1,n);
while(m--){
int x,y;
nMax = -1;
nMin = My_Max;
scanf("%d %d",&x,&y);
Query(1,x,y);
printf("%d\n",nMax-nMin);
}
}
return 0;
}