Balanced Lineup poj3264 线段树

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


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值