版权声明:但行好事,莫问前程。 https://blog.csdn.net/Li_Hongcheng/article/details/81228689
RMQ线段树
区间最大值最小值
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=50050;
#define inf 9999999999;
struct node
{
int l,r;
int Max,Min;
} tree[maxn<<2];
void pushup(int rt)
{
tree[rt].Min=min(tree[rt<<1].Min,tree[rt<<1|1].Min);
tree[rt].Max=max(tree[rt<<1].Max,tree[rt<<1|1].Max);
}
void build(int l,int r,int rt)
{
tree[rt].l=l;
tree[rt].r=r;
if(l==r)
{
int a;
scanf("%d",&a);
tree[rt].Min=tree[rt].Max=a;
return ;
}
int mid=(l+r)>>1;
build(l,mid,rt<<1);
build(mid+1,r,rt<<1|1);
pushup(rt);
}
int querymax(int l,int r,int rt)
{
if(tree[rt].l==l && tree[rt].r == r)
{
return tree[rt].Max;
}
int mid=(tree[rt].l+tree[rt].r)>>1;
if(mid>= r) return querymax(l,r,rt<<1);
else if(l > mid) return querymax(l,r,rt<<1|1);
else return max(querymax(l,mid,rt<<1), querymax(mid + 1,r,rt<<1|1));
}
int querymin(int l,int r,int rt)
{
if(tree[rt].l==l&&tree[rt].r==r)
{
return tree[rt].Min;
}
int mid =(tree[rt].l+tree[rt].r)>>1;
if(mid>=r) return querymin(l,r,rt<<1);
else if(l > mid) return querymin(l,r,rt<<1|1);
else return min(querymin(l, mid,rt<<1), querymin( mid + 1, r,rt<<1|1));
}
int main()
{
int n,q,ans1,ans2;
while(~scanf("%d%d",&n,&q))
{
build(1,n,1);
while(q--)
{
int s,t;
scanf("%d%d",&s,&t);
ans1=querymin(s,t,1);
ans2=querymax(s,t,1);
printf("%d\n",ans2-ans1);
}
}
}