poj 3264 Balanced Lineup (线段树)

题意:http://poj.org/problem?id=3264

这里需要用到线段树的查询,不过特别的是,它需要查找两个值,最大值和最小值,在查找操作中稍加处理即可。

#include <iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn=5e4+5;
int height[maxn];// 最长区间长度
struct node{
    int left,right,high,low;
}btree[3*maxn]; // 设置根节点下标是1,则左孩子是2*dex,右孩子下标是2*dex+1.
void build(int root,int l,int r){  //主函数数组里的dex对应这里的l,r
    btree[root].left=l;  //root对应树和各种子树的根节点
    btree[root].right=r;
    if(l==r){
        btree[root].low=btree[root].high=height[l];
        return ;
    }
    int mid=(l+r)/2;
    build(root*2,l,mid);
    build(root*2+1,mid+1,r);
    btree[root].high=max(btree[2*root].high,btree[2*root+1].high); //递归回溯赋值给双亲结点
    btree[root].low=min(btree[2*root].low,btree[2*root+1].low);
}
void query(int root,int L,int R,int &higher,int &lower){
    if(L<=btree[root].left&&R>=btree[root].right){
        higher=max(btree[root].high,higher);
        lower=min(btree[root].low,lower);
        return ;
    }
    int mid=(btree[root].left+btree[root].right)/2;
    if(L<=mid)query(root*2,L,R,higher,lower); // L,R不要弄错,否则会数组越界
    if(R>mid)query(2*root+1,L,R,higher,lower);
}
int main(int argc, char *argv[]) {
    //freopen("cin.txt","r",stdin);
    int N,Q,i;
    while(cin>>N>>Q){
        for(i=1;i<=N;i++)scanf("%d",&height[i]);
        build(1,1,N);
        for(i=1;i<=Q;i++){
            int a,b,higher=0,lower=(int)(1e6+1);
            scanf("%d%d",&a,&b);
            query(1,a,b,higher,lower);
            printf("%d\n",higher-lower);
        }
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值