poj 3875 RMQ或线段树求区间最值
以前用RMQ做过,刚好最近在做线段树,就用线段树也做了下,1A~
两个域,分别保存当前结点下面的最大值和最小值
View Code
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 55555;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
int MIN[maxn<<2];
int MAX[maxn<<2];
int min(int a,int b){
return a<b?a:b;
}
int max(int a,int b){
return a>b?a:b;
}
void pushup(int rt){
MIN[rt]=min(MIN[rt<<1],MIN[rt<<1|1]);
MAX[rt]=max(MAX[rt<<1],MAX[rt<<1|1]);
}
void build(int l,int r,int rt)
{
if(l==r){
scanf("%d",&MAX[rt]);
MIN[rt]=MAX[rt];
return ;
}
int m=(l+r)>>1;
build(lson);build(rson);
pushup(rt);
}
int query(int L,int R,int l,int r,int rt,bool flag)
{
if(L <= l && r <= R){
if(flag) return MAX[rt];
else return MIN[rt];
}
int m=(l+r)>>1;
int ret1=0,ret2=100000000;
if(L<=m)
{
if(flag) ret1=max(ret1,query(L,R,lson,flag));
else ret2=min(ret2,query(L,R,lson,flag));
}
if(R>m)
{
if(flag) ret1=max(ret1,query(L,R,rson,flag));
else ret2=min(ret2,query(L,R,rson,flag));
}
return flag?ret1: ret2;
}
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
build(1,n,1);
while(m--)
{
int a,b;
scanf("%d%d",&a,&b);
int mi=query(a,b,1,n,1,false);
int mx=query(a,b,1,n,1,true);
printf("%d\n",mx-mi);
}
}
}