POJ 3264 线段树

来源:互联网 发布:最有效防御sql注入x 编辑:程序博客网 时间:2024/04/29 06:56
//11052945c00h00g3264Accepted3340K1672MSC++1483B2012-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;}