Line segment tree to find the maximum interval (template 1)

Line segment tree to find the maximum interval (template 1)

Question:
Given an n-bit array and two operations:

  • ​Operation 1: Modify the value of a position in the array
  • ​Operation 2: Query the maximum value of a certain interval in the array

Template question

struct SegmentTree{
    
    
	int l,r;
	int dat;
	#define l(x) tree[x].l
    #define r(x) tree[x].r
    #define dat(x) tree[x].dat
}tree[maxn*4];
int a[maxn],n,m;

void build(int p,int l,int r){
    
    
	l(p)=l,r(p)=r;
	if(l==r){
    
    dat(p)=a[l];return;}
	int mid=(l+r)/2;
	build(p*2,l,mid);
	build(p*2+1,mid+1,r);
	dat(p)=max(dat(p*2),dat(p*2+1));
}

/*void lazy(int p){
	if(add(p)){
		sum(p*2)+=add(p)*(r(p*2)-l(p*2)+1);
		sum(p*2+1)+=add(p)*(r(p*2+1)-l(p*2+1)+1);
		add(p*2)+=add(p);
		add(p*2+1)+=add(p);
		add(p)=0;
	}
}*/

void change(int p,int x,int z){
    
    
	if(l(p)==r(p)){
    
    
		dat(p)=z;return;
	}
	int mid=(l(p)+r(p))/2;
	if(x<=mid) change(p*2,x,z);
    if(x>mid) change(p*2+1,x,z);
	dat(p)=max(dat(p*2),dat(p*2+1));
}

LL ask(int p,int l,int r){
    
    
	if(l<=l(p)&&r>=r(p)) return dat(p);
    int mid=(l(p)+r(p))/2;
	LL ans=-1*inf;
    if(l<=mid) ans=max(ans,ask(p*2,l,r));
    if(r>mid) ans=max(ans,ask(p*2+1,l,r));
    return ans;
}

int main(){
    
    
	cin>>n>>m;
	for(int i=1;i<=n;i++)
		cin>>a[i];
	build(1,1,n);
	while(m--){
    
    
        int op,x,y,z;
		scanf("%d%d%d",&op,&x,&y);
		if(op==1){
    
    
			change(1,x,y);
		}
		else {
    
    if(x>y)swap(x,y);cout<<ask(1,x,y)<<endl;};
	}
}

Guess you like

Origin blog.csdn.net/weixin_44986601/article/details/105759349