POJ3264 线段树模板

原题链接:POJ3264

解析:我拿本题来熟悉线段树模板的,这个应该算是裸题了。

代码示例:

#include<iostream>
#include<cstdio>
using namespace std;
const int INF = 2e9;
int minV = INF;
int maxV = -INF;
struct CNode{
	int l,r;
	int minv,maxv;
	int Mid(){
		return (l+r)/2;
	}
}tree[800020];
void BuildTree(int root,int l,int r){
	tree[root].l = l;
	tree[root].r = r;
	tree[root].minv = INF;
	tree[root].maxv = -INF;
	if(l != r){
		BuildTree(2*root+1,l,(l+r)/2);
		BuildTree(2*root+2,(l+r)/2+1,r);
	}
	return;
}
void Insert(int root,int i,int v){
	if(tree[root].l == tree[root].r){
		tree[root].minv = tree[root].maxv = v;
		return;
	}
	tree[root].minv = min(tree[root].minv,v);
	tree[root].maxv = max(tree[root].maxv,v);
		if(tree[root].Mid() >= i)
			Insert(2*root+1,i,v);
		else Insert(2*root+2,i,v);
}
void Query(int root,int s,int e){
	if(tree[root].minv >= minV && tree[root].maxv <= maxV)
		return;
	if(tree[root].l == s && tree[root].r == e){
		minV = min(minV,tree[root].minv);
		maxV = max(maxV,tree[root].maxv);
		return;
	}
	if(e <= tree[root].Mid())	Query(2*root+1,s,e);
	else if(s > tree[root].Mid())	Query(2*root+2,s,e);
	else{
		Query(2*root+1,s,tree[root].Mid());
		Query(2*root+2,tree[root].Mid()+1,e); 
	}
}
int main(){
	int n,q,h;
	scanf("%d%d",&n,&q);
	BuildTree(0,1,n);
	for(int i = 1;i <= n;i++){
		scanf("%d",&h);
		Insert(0,i,h);
	}	
	int s,e;
	for(int i = 0;i < q;i++){
		minV = INF;
		maxV = -INF;
		scanf("%d%d",&s,&e);
		Query(0,s,e);
		printf("%d\n",maxV-minV);
	}
	return 0;
}

 

转载于:https://www.cnblogs.com/long98/p/10352198.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值