一道线段树水题,因为一小段代码错误 卡了半天。。实在不应该。。
题意
给你 N 头牛和 N 头牛的身高,再给你一个区间,求这个区间内部最高的牛和最矮的牛的身高差。
典型线段树,开两个线段树,然后一个求最大,一个求最小,然后相减就完事了。
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
typedef long long int LL;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define root 1,n,1
const int maxn = 500005;
int mx[maxn];
int mi[maxn];
int n,m,s,e;
void pushmx(int rt)
{
mx[rt]=max(mx[rt<<1],mx[rt<<1|1]);
}
void pushmi(int rt)
{
mi[rt]=min(mi[rt<<1],mi[rt<<1|1]);
}
void build(int l,int r,int rt)
{
if(l==r)
{
int temp;
scanf("%d",&temp);
mx[rt]=temp;
mi[rt]=temp;
return ;
}
int m=(l+r)>>1;
build(lson);
build(rson);
pushmx(rt);
pushmi(rt);
}
int qe_max(int l,int r,int rt,int L,int R)
{
if(L<=l&&R>=r)
return mx[rt];
int m=(l+r)>>1;
int ret=0;
if(L<=m)
{
ret=max(ret,qe_max(lson,L,R));
}
if(R>m)
{
ret=max(ret,qe_max(rson,L,R));
}
return ret;
}
int qe_min(int l,int r,int rt,int L,int R)
{
if(L<=l&&R>=r)
return mi[rt];
int m=(l+r)>>1;
int ret=1001001;
if(L<=m)
{
ret=min(ret,qe_min(lson,L,R));
}
if(R>m)
{
ret=min(ret,qe_min(rson,L,R));
}
return ret;
}
int main()
{
scanf("%d%d",&n,&m);
build(root);
for(int i=1;i<=m;i++)
{
scanf("%d%d",&s,&e);
printf("%d\n",qe_max(root,s,e)-qe_min(root,s,e));
}
return 0;
}