线段树入门

题意:

            给定Q(1 ≤ Q≤ 200,000)个数A1,A2… AQ,,多次求任一区间[Ai,Aj]中最大数和最小数的差。


*下面先介绍一种优秀的数据结构!线段树(Interval Tree), 查找和更新操作都是nlog2(n);

树:是一棵树,而且是一棵二叉树。
    线段:树上的每个节点对应于一个线段(还是叫“区间”更容易理解,区间的起点和终点通常为整数);
    同一层的节点所代表的区间,相互不会重叠。同一层节点所代表的区间,加起来是个连续的区间。
    叶子节点的区间是单位长度,不能再分了。


下面我们先做一分析一下所需要的数据结构:

struct node
{
    int l,r;该节点的表示区间[l,r]
    int nmin,nmax;//记录区间 [l,r]上的最大值和最小值
    node *pleft,*pright;//左右孩子
};

线段树三部曲:(1)先建立一个具有n 节点的线段树。

                         (2)然后插入节点信息,复杂度是O(log2(n));

                         (3)查询区间[s,e],返回结果。

下面代码:

/*
*给定Q(1 ≤ Q≤ 200,000)个数A1,A2… *AQ,,多次求任一区间[Ai,Aj]中最大数和最小数的差。
*/
#include <iostream>
#include <string>
#include <cstdio>
using namespace std;
#define MAX -0x7fffffff
#define MIN 0x7fffffff
struct node
{
    int l,r;
    int nmin,nmax;//record the max number or min number the range[l,r]
    node *pleft,*pright;
};
int nCount=0;//record the sum of all node
int nmax,nmin;
node Tree[1000000];//其实两倍叶子节点数目-1就够了
void BuildTree(node *p,int l,int r)
{
    p->l=l;
    p->r=r;
    p->nmax=MAX;
    p->nmin=MIN;
    if(l!=r)
    {
       nCount++;
       p->pleft=Tree+nCount;
       nCount++;
       p->pright=Tree+nCount;
       BuildTree(p->pleft,l,(l+r)>>1);
       BuildTree(p->pright,((l+r)>>1)+1,r);
    }
}
void Insert(node *p,int i,int v)
{
   if(p->l==i&&p->r==i)
   {
      p->nmax=p->nmin=v;
      return ;
   }
   //update current node
   p->nmax=max(p->nmax,v);
   p->nmin=min(p->nmin,v);
   if(i<=(p->l+p->r)/2)
      Insert(p->pleft,i,v);
   else
      Insert(p->pright,i,v);
}
//查询区间[s,e]中的最小值和最大值,如果更优就记在全局变量里
void query(node *p,int s,int e)
{
    if(p->l==s&&p->r==e)
    {
       nmin=min(p->nmin,nmin);
       nmax=max(p->nmax,nmax);
       return ;
    }
    if(e<=(p->l+p->r)/2)
    {
       query(p->pleft,s,e);
    }
    else if(s>=(p->l+p->r)/2+1)
    {
       query(p->pright,s,e);
    }
    else
    {
       query(p->pleft,s,(p->l+p->r)/2);
       query(p->pright,(p->l+p->r)/2+1,e);
    }
}
int main()
{
    int n,q,num;
    int i,s,e;
    scanf("%d%d",&n,&q);//输入节点总数,查询次数
    nCount=0;
    BuildTree(Tree,1,n);//建树
    for(i=1; i<=n; i++)
    {
        scanf("%d",&num);
        Insert(Tree,i,num);
    }
    for(i=0;i<q;i++)
    {
       scanf("%d%d",&s,&e);
       nmax=MAX;
       nmin=MIN;
       query(Tree,s,e);
       printf("%d\n",nmax-nmin);
    }
    return 0;
}






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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值