POJ 3264 线段树

//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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值