poj3264 线段树

再次理解线段树。比第一次又有了更深刻的认识,虽然还不能完全靠自己写出来,但自己慢慢的去摸索,一定能慢慢理解那个套路了。加油,拿下线段树。

同时,推荐北大郭炜讲的线段树。

poj3264

#include <iostream>
#include <algorithm>
#include <numeric>

using namespace std;
#define MY_MIN 99999999
#define MY_MAX -99999999
struct CNode{
int L,R;
int nMin,nMax;
CNode *pLeft,*pRight;
};

int min ( const int a, const int b ) {
return (b<a)?b:a;
}
int max ( const int a, const int b ) {
return (b<a)?a:b;
}


int nMax,nMin; //用于记录最大值和最小值
CNode Tree[1000000]; //一般为叶子节点的两倍
int nCount=0; //总节点数

void Build(CNode *pRoot,int L,int R){
//建线段树

pRoot->L=L;pRoot->R=R;
pRoot->nMin=MY_MIN;pRoot->nMax=MY_MAX;
if(L!=R){
nCount++;
pRoot->pLeft=Tree+nCount;
nCount++;
pRoot->pRight=Tree+nCount;
Build(pRoot->pLeft,L,(L+R)/2);
Build(pRoot->pRight,(L+R)/2+1,R);
}
}

void Insert(CNode *pRoot,int i,int v){
//将第i个数(其值为v)插入到线段树中
if(pRoot->L==i && pRoot->R==i){
pRoot->nMin=pRoot->nMax=v;
return;
}
pRoot->nMax=max(pRoot->nMax,v);
pRoot->nMin=min(pRoot->nMin,v);
if(i<=(pRoot->R+pRoot->L)/2){
Insert(pRoot->pLeft,i,v);
}
else{
Insert(pRoot->pRight,i,v);
}
}

void Query(CNode *pRoot,int L,int R){
if( pRoot->nMin>= nMin && pRoot->nMax <= nMax) //这没理解到。哎。
return;
if(pRoot->L==L && pRoot->R==R)
{
nMax=max(pRoot->nMax,nMax); //这当时也没注意到要用函数。
nMin=min(pRoot->nMin,nMin);
return;
}
else if(R<=(pRoot->R+pRoot->L)/2){
Query(pRoot->pLeft,L,R);
}
else if(L>=(pRoot->R+pRoot->L)/2+1){
Query(pRoot->pRight,L,R);
}
else{
Query(pRoot->pLeft,L,(pRoot->R+pRoot->L)/2);
Query(pRoot->pRight,(pRoot->R+pRoot->L)/2+1,R);
}
}

int main(){
int m,n,x,y;
int v,i;
scanf("%d %d",&m,&n);
Build(Tree,1,m);
for(i=1;i<=m;i++){
scanf("%d",&v);
Insert(Tree,i,v);
}
for(i=1;i<=n;i++){
scanf("%d%d",&x,&y);
nMax = MY_MAX;
nMin = MY_MIN;
Query(Tree,x,y);
printf("%d\n",nMax-nMin);
}
return 0;
}

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值