http://poj.org/problem?id=3264
线段树步骤:建树 插入数据 更新 查询
这个题算是相当基本了吧。
第一遍是照着老师的pdf敲的。
#include <iostream>
#include <algorithm>
#include <cstdio>
#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 nMax,nMin;
CNode Tree[100005];//两倍叶子节点+1
int nCount=0;//总节点数目
void BuildTree(CNode *pRoot,int L,int R){
pRoot->L=L;
pRoot->R=R;
pRoot->nMax=MY_MAX;
pRoot->nMin=MY_MIN;
if (L!=R){
nCount++;
pRoot->pleft=Tree+nCount;
nCount++;
pRoot->pright=Tree+nCount;
BuildTree(pRoot->pleft,L,(L+R)/2);
BuildTree(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->nMax=pRoot->nMin=v;
return ;
}
pRoot->nMin=min(pRoot->nMin,v);
pRoot->nMax=max(pRoot->nMax,v);
if (i<=(pRoot->L+pRoot->R)/2)
Insert(pRoot->pleft,i,v);
else
Insert(pRoot->pright,i,v);
}
void Query(CNode *pRoot,int s,int e){ //查询区间[s,e]中的最小值和最大值,如果更优就记在全局变量里
if (pRoot->nMin>=nMin&&pRoot->nMax<=nMax)
return;
if (s==pRoot->L&&e==pRoot->R){
nMin=min(pRoot->nMin,nMin);
nMax=max(pRoot->nMax,nMax);
return;
}
if (e<=(pRoot->L+pRoot->R)/2)
Query(pRoot->pleft,s,e);
else if (s>=(pRoot->L+pRoot->R)/2+1)
Query(pRoot->pright,s,e);
else {
Query(pRoot->pleft,s,(pRoot->L+pRoot->R)/2);
Query(pRoot->pright,(pRoot->L+pRoot->R)/2+1,e);
}
}
int main(){
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
int n,q,h;
int i,j,k;
scanf("%d%d",&n,&q);
nCount=0;
BuildTree(Tree,1,n);
for (i=1;i<=n;i++){
scanf("%d",&h);
Insert(Tree,i,h);
}
for (k=0;k<q;k++){
scanf("%d%d",&i,&j);
nMax=MY_MAX;
nMin=MY_MIN;
Query(Tree,i,j);
printf("%d\n",nMax-nMin);
}
return 0;
}