Visitors hit counter dreamweaver

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;
}

 

 

 

posted @ 2012-02-21 21:11  Jason Damon  阅读(1404)  评论(1编辑  收藏  举报