//11052945 c00h00g 3264 Accepted 3340K 1672MS C++ 1483B 2012-11-26 18:34:28
//线段树一个很基本的题目,一段时间不写又生疏了
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
#include<algorithm>
using namespace std;
struct Node{
int a,b;
int _max,_min;
Node(){
_max=_min=-1;
}
};
Node tree[50005*4];
void build(int root,int a,int b){
tree[root].a=a;
tree[root].b=b;
if(a==b){
int tmp;
scanf("%d",&tmp);
tree[root]._max=tmp;
tree[root]._min=tmp;
return;
}
int m=(a+b)>>1;
build(root*2,a,m);
build(root*2+1,m+1,b);
tree[root]._max=max(tree[root*2]._max,tree[root*2+1]._max);
tree[root]._min=min(tree[root*2]._min,tree[root*2+1]._min);
}
int Max,Min;
void find_max_min(int root,int l,int r,int a,int b){
if(l==a&&r==b){
//关键是在这儿寻找最大值最小值
Max=max(Max,tree[root]._max);
Min=min(Min,tree[root]._min);
return;
}
int m=(l+r)>>1;
if(b<=m)
find_max_min(root*2,tree[root*2].a,tree[root*2].b,a,b);
else if(a>m)
find_max_min(root*2+1,tree[root*2+1].a,tree[root*2+1].b,a,b);
else{
find_max_min(root*2,tree[root*2].a,tree[root*2].b,a,m);
find_max_min(root*2+1,tree[root*2+1].a,tree[root*2+1].b,m+1,b);
}
}
int main(){
int N,Q,m,n;
scanf("%d%d",&N,&Q);
build(1,1,N);
while(Q--){
scanf("%d%d",&m,&n);
Max=-INT_MAX;
Min=INT_MAX;
find_max_min(1,1,N,m,n);
printf("%d\n",Max-Min);
}
return 0;
}
POJ 3264 线段树
最新推荐文章于 2019-01-08 02:54:15 发布