POJ3264(线段树求最大最小值)

 1.首先注意:查询函数中的ans变量(因为需要递归下去)不能使用全局变量。

2.查询函数中因为递归调用查询函数,尽量减少递归调用的次数,否则容易超时。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<string>
using namespace std;
const int maxn=50005;
const int inf=0x3f3f3f3f;
int tree[2][maxn<<2];
int n,m,L,R;
void pushup(int rt)
{
    tree[1][rt]=max(tree[1][rt<<1],tree[1][rt<<1|1]);
    tree[0][rt]=min(tree[0][rt<<1],tree[0][rt<<1|1]);
}
void build_tree(int l,int r,int rt)
{
    if(l==r)
    {
        scanf("%d",&tree[0][rt]);
        tree[1][rt]=tree[0][rt];
        return;
    }
    int m=(l+r)>>1;
    build_tree(l,m,rt<<1);
    build_tree(m+1,r,rt<<1|1);
    pushup(rt);
}
int query(int l,int r,int rt,int p)
{
    if(L<=l&&r<=R)
    {
        return tree[p][rt];
    }
    int m=(l+r)>>1;
    int ans;
    p==0?ans=inf:ans=0;
    if(L<=m)
    {
        if(p)
            ans=max(ans,query(l,m,rt<<1,1));
        else
            ans=min(ans,query(l,m,rt<<1,0));
    }
    if(m<R)
    {
        if(p)
            ans=max(ans,query(m+1,r,rt<<1|1,1));
        else
            ans=min(ans,query(m+1,r,rt<<1|1,0));
    }
    return ans;
}
int main()
{
    scanf("%d%d",&n,&m);
    build_tree(1,n,1);
    for(int i=0; i<m; i++)
    {
        scanf("%d%d",&L,&R);
        printf("%d\n",query(1,n,1,1)-query(1,n,1,0));
    }
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值