hdu1754 单点更新+求区间最值(线段树)

    与前几题不同,此题需要维护的是区间的最大值。

    简单的说,单点更新时,在递归回溯的时候要push_up,更新区间的最大值。

    没有懒惰标记,查询就是用ans和覆盖区间tree[x].maxn去比大小。算是线段树的裸题了。

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
const int maxn = 200000+5;
using namespace std;
int n,m,a[200000+5],x,y;
char s;

struct node{
	int l,r;
	int maxn;
	int lazy;
	
}tree[maxn*3];

void push_up(int x)
{
	tree[x].maxn = max(tree[x<<1].maxn,tree[x<<1|1].maxn);
}

void build(int x,int l,int r)
{
	tree[x].l = l,tree[x].r = r;
	tree[x].maxn = tree[x].lazy = 0;
	if(l==r) tree[x].maxn = a[l];
	else{
		int mid = (l+r)/2;
		build(x<<1,l,mid);
		build(x<<1|1,mid+1,r);
		push_up(x);
	}
}

void update(int x,int id,int y)//将第id个同学的分数改为y
{
	int L=tree[x].l, R=tree[x].r;
	if(L==id&&R==id){
		tree[x].maxn = y;
	}
	else{
		int mid = (L+R)/2;
		if(id<=mid)
		 update(x<<1,id,y);
		if(id>mid)
		 update(x<<1|1,id,y);
		push_up(x);
	}
} 

int query(int x,int l,int r)
{
	int ans = 0;
	int L=tree[x].l, R=tree[x].r;
	if(l<=L&&r>=R){
		ans = max(ans,tree[x].maxn);
	}
	else{
		int mid = (L+R)/2;
		if(l<=mid)
		 ans = max(ans,query(x<<1,l,r));
		if(r>mid)
		 ans = max(ans,query(x<<1|1,l,r));
	}
	return ans;
}

int main()
{
	//freopen("d://test.txt","r",stdin);
	while(~scanf("%d%d",&n,&m))
	{
		for(int i=1;i<=n;i++)
		 scanf("%d",&a[i]);
		build(1,1,n);
		for(int i=0;i<m;i++)
		{
			cin>>s;
			scanf("%d%d",&x,&y);
			if(s=='Q'){
				cout<<query(1,x,y)<<endl;
			}
			else {
				update(1,x,y);
			}
		}
	}
	return 0;
}

    ps:想做完扫描线以后统一的写一下线段树的心得,即“套路”。定个小目标吧,到初四前完成线段树的一个专题训练(10)题,并写一篇总结。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

总想玩世不恭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值