poj 3264

第一次写线段树,参考了人家的才会.

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 50100;
const int My_Max = 999999999;
struct Node{
      int l,r,Min,Max;
};

int h[maxn];
Node st[maxn<<2];
int nMax,nMin;

void BuildTree(int rt,int l,int r){
        st[rt].l = l;
        st[rt].r = r;
        if(l == r)
           st[rt].Max = st[rt].Min = h[l];
        else{
           int mid = (l + r) >> 1;
           BuildTree(rt << 1, l, mid       );
           BuildTree(rt << 1 | 1, mid +1, r);
           st[rt].Max = max(st[rt << 1].Max, st[rt << 1 | 1].Max);
           st[rt].Min = min(st[rt << 1].Min, st[rt << 1 | 1].Min);
        }
}
void Query(int rt,int l,int r){
        if(nMin <= st[rt].Min && nMax >= st[rt].Max)
           return ;
        int mid = (st[rt].l + st[rt].r) >> 1;
        if(l == st[rt].l && r == st[rt].r){
            nMax = max( st[rt].Max, nMax);
            nMin = min( st[rt].Min, nMin);
           }
        else if(mid < l)
            Query(rt << 1 | 1, l, r);
        else if(mid >= r)
            Query(rt << 1    , l, r);
        else{
            Query(rt << 1 | 1, mid + 1, r);
            Query(rt << 1    , l, mid);
            }
}
int main(){
        int n,m;
        while(~scanf("%d %d",&n,&m)){
            for(int i = 1; i <= n; ++i)
               scanf("%d",&h[i]);
            BuildTree(1,1,n);
            while(m--){
                 int x,y;
                 nMax = -1;
                 nMin = My_Max;
                 scanf("%d %d",&x,&y);
                 Query(1,x,y);
                 printf("%d\n",nMax-nMin);
            }
        }
   return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值