/*******
线段树询问最大值和最小值 差问题
*************/
#include<iostream>
#include<cstdlib>
#define inf 0x3f3f3f3f
using namespace std;
const int maxn = 1e6+50;
struct node
{
int l;
int r;
int min1;
int max1;
}Segtr[maxn*4];
void build(int rt, int l ,int r)
{
Segtr[rt].l = l;
Segtr[rt].r = r;
Segtr[rt].min1 = 0;
Segtr[rt].max1 = 0;
if(r == l)
{
cin>>Segtr[rt].min1;
Segtr[rt].max1 = Segtr[rt].min1;
return;
}
int mid = (l+r)>>1;
build(rt*2+1, l, mid);
build(rt*2+2, mid+1, r);
Segtr[rt].max1 = max(Segtr[rt*2+1].max1, Segtr[rt*2+2].max1);
Segtr[rt].min1 = min(Segtr[rt*2+1].min1, Segtr[rt*2+2].min1);
}
int mx, mi;
void query(int rt, int L, int R)
{
int l =Segtr[rt].l;
int r = Segtr[rt].r;
if(L == l&&r == R)
{
mx = max(Segtr[rt].max1, mx);
mi = min(Segtr[rt].min1, mi);
return;
}
int mid = (l+r)>>1;
if(R <= mid)
{
query(rt*2+1, L, R);
}
else if(L > mid)
{
query(rt*2+2, L, R);
}
else
{
query(rt*2+1, L ,mid);
query(rt*2+2, mid+1, R);
}
return;
}
void init()
{
mx = -1;
mi = inf;
}
int main()
{
ios_base::sync_with_stdio(false);
int n,q;
cin>>n>>q;
build(0, 1, n);
for(int i = 0;i < q;i++)
{
int x, y;
cin>>x>>y;
init();
query(0, x, y);
cout << (mx- mi)<<endl;
}
return 0;
}
线段树最值查询
最新推荐文章于 2024-05-25 11:28:51 发布