与前几题不同,此题需要维护的是区间的最大值。
简单的说,单点更新时,在递归回溯的时候要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)题,并写一篇总结。