1270. 数列区间最大值(线段树)

1270. 数列区间最大值
若数据较大,用暴力方法可能会超时
建立线段树,改变每个线段区间的最大值
每次访问 [ x , y ] 时判断 [ x , y ] 在区间的位置,是否需要再进入子区间

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=100010;
int a[N],ma;
struct no
{
	int r;//左断电 
	int l;//右端点 
	int ma;//区间最大值 
}tree[4*N];
void build(int left,int right,int u)
{
	tree[u].l=left;//区间左端点 
	tree[u].r=right;//区间右断电 
	if(right==left)
	{
		tree[u].ma=a[left];//如果是单区间,最大值是本身 
		return;
	}
	build(left,(left+right)>>1,u<<1);//建立左子区间 
	build(((left+right)>>1)+1,right,(u<<1)+1);//建立右子区间 
	tree[u].ma=max(tree[u<<1].ma,tree[(u<<1)+1].ma);//父区间的最大值是两个子区间的最大值 
}
void query(int u,int x,int y)
{
	if(tree[u].l>=x&&tree[u].r<=y)//这个区间在[x,y]以内 
	{
	    ma=max(ma,tree[u].ma);//更新最大值 
	    return;
	}
	if(tree[u<<1].r>=x) query(u<<1,x,y);//x在左子区间 
	if(tree[(u<<1)+1].l<=y) query((u<<1)+1,x,y);//y在右子区间 
}
int main()
{
	int i,j,n,m;
	scanf("%d %d",&n,&m);
	for(i=1;i<=n;i++)
		scanf("%d",&a[i]);
	build(1,n,1);//建立1号区间,[1,n] 
	for(i=1;i<=m;i++)
	{
		int x,y;
		ma=-(1<<31)+1;//初始化必须最小 
		scanf("%d %d",&x,&y);
		query(1,x,y);//从1号区间开始寻找 
		printf("%d\n",ma);
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值