线段树水题,寻找区间最大最小值。
只要建树还有查询操作就好了,更新没必要写。。
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <queue>
#include <stack>
#include <climits>
#define MID(x,y) ((x+y)>>1)
#define L(x) (x<<1)
#define R(x) (x<<1|1)
using namespace std;
const int MAX = 50010;
struct Tnode{int min,max,l,r;};
Tnode node[MAX*4];
int v[MAX];
int mmin,mmax;
void init()
{
memset(node,0,sizeof(node));
}
void Build(int t,int l,int r)
{
node[t].l = l;
node[t].r = r;
if( l == r - 1 )
{
node[t].min = node[t].max = v[l];
return ;
}
int mid = MID(l,r);
Build(L(t),l,mid);
Build(R(t),mid,r);
node[t].max = max(node[L(t)].max,node[R(t)].max);
node[t].min = min(node[L(t)].min,node[R(t)].min);
}
void Query(int t,int l,int r)
{
if( node[t].l == l && node[t].r == r )
{
mmax = max(node[t].max,mmax);
mmin = min(node[t].min,mmin);
return ;
}
int mid = MID(node[t].l,node[t].r);
if( l >= mid )
Query(R(t),l,r);
else
if( r <= mid )
Query(L(t),l,r);
else
{
Query(R(t),mid,r);
Query(L(t),l,mid);
}
}
int main()
{
int n,m,x,y;
while( ~scanf("%d%d",&n,&m) )
{
init();
for(int i=0; i<n; i++)
scanf("%d",&v[i]);
Build(1,0,n);
while( m-- )
{
scanf("%d%d",&x,&y);
mmin = INT_MAX; mmax = 0;
Query(1,x-1,y);
printf("%d\n",mmax - mmin);
}
}
return 0;
}