poj3264 1641ms interval tree

#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
/*Interval Tree 入门第一题
 *虽然是按照讲义一步步来的,但感觉也学到了很多
 *这两天多写写线段树的题目。
 *区间树用途:区间更新,区间查询
 *过几天整理一份线段树的文章出来
 */
const int INF = 0x3f3f3f3f;
int ans_max = -INF;
int ans_min = INF;
const int MAX_N = 50000;
struct Node
{
    int L;
    int R;
    int minv,maxv;
    int Mid()
    {
        return (L+R)/2;
    }
};
Node Inteval_Tree[MAX_N<<2];
void BuildTree(int root,int l,int r)
{
    Inteval_Tree[root].L = l;
    Inteval_Tree[root].R = r;
    Inteval_Tree[root].minv = INF;
    Inteval_Tree[root].maxv = -INF;
    if(l!=r)
    {
        BuildTree(root*2+1,l,(l+r)/2);
        BuildTree(root*2+2,(l+r)/2+1,r);
    }
}
void insert(int root,int i,int value)
{
    if(Inteval_Tree[root].L == Inteval_Tree[root].R)
    {
        Inteval_Tree[root].minv = Inteval_Tree[root].maxv = value;
        return;
    }
    Inteval_Tree[root].minv = min(Inteval_Tree[root].minv,value);
    Inteval_Tree[root].maxv = max(Inteval_Tree[root].maxv,value);
    if(i<=Inteval_Tree[root].Mid())
        insert(2*root+1,i,value);
    else
        insert(2*root+2,i,value);
}
void Query(int root,int s,int e)
{
//查询区间[s,e]中的最小值和最大值,如果更优就记在全局变量里
//minV和maxV里
    if(Inteval_Tree[root].maxv<=ans_max&&Inteval_Tree[root].minv>=ans_min)
        return;
    if(Inteval_Tree[root].L==s&&Inteval_Tree[root].R==e)
    {
        ans_max = max(ans_max,Inteval_Tree[root].maxv);
        ans_min = min(ans_min,Inteval_Tree[root].minv);
        return;
    }
    if(e<=Inteval_Tree[root].Mid())
        Query(2*root+1,s,e);
    else if(s>Inteval_Tree[root].Mid())
        Query(2*root+2,s,e);
    else
    {
        Query(2*root+1,s,Inteval_Tree[root].Mid());
        Query(2*root+2,Inteval_Tree[root].Mid()+1,e);
    }
}
int main()
{
    int n,q,val;
    int s,e;
    scanf("%d%d",&n,&q);
    BuildTree(0,1,n);
    for(int i = 1; i<=n; ++i)
    {
        scanf("%d",&val);
        insert(0,i,val);
    }
    while(q--)
    {
        scanf("%d%d",&s,&e);
        ans_max = -INF;
        ans_min = INF;
        Query(0,s,e);
        printf("%d\n",ans_max-ans_min);
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值