Balanced Lineup poj3264 线段树

来源:互联网 发布:js使用java函数 编辑:程序博客网 时间:2024/05/22 17:47

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 -99999999struct CNode{int L,R;//区间的起点和终点int nMin,nMax;//本区间的最大最小值CNode *pleft,*pright;};int nMax,nMin;CNode Tree[100005];//两倍叶子节点+1int 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_JUDGEfreopen("in.txt","r",stdin);#endifint 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;}


原创粉丝点击