Templates - segment tree

Here is an example interval maximum value, to be modified into other operations, irrespective of the value of each note modify operation function, and the returned query.

Here the smallest element section sets the maximum value is -1 (indicating a result of the current interval does not intersect the section of the query).

Note that because the way incoming calls l and r are (1, n), so this segment tree (including a) from 1 actually counted.

Finally, be careful burst MAXM.

const int MAXM=200000;
int a[MAXM+5],st[(MAXM<<2)+5];

inline void pushup(int o){
    st[o]=max(st[o<<1],st[o<<1|1]);
}
 
void build(int o,int l,int r){
    if(l==r) st[o]=a[l];
    else{
        int m=l+((r-l)>>1);
        build(o<<1,l,m);
        build(o<<1|1,m+1,r);
        pushup(o);
    }
}
 
void update(int o,int l,int r,int id,int v){
    if(l==r) st[o]=v;
    else{
        int m=l+((r-l)>>1);
        if(id<=m) update(o<<1,l,m,id,v);
        else update(o<<1|1,m+1,r,id,v);
        pushup(o);
    }
}
 
int query(int o,int l,int r,int a,int b){
    if(r<a||l>b) return -1;
    if(a<=l&&r<=b) return st[o];
    int m=l+((r-l)>>1);
    int p1=query(o<<1,l,m,a,b),p2=query(o<<1|1,m+1,r,a,b);
    return max(p1,p2);
}
 

Guess you like

Origin www.cnblogs.com/Yinku/p/10936478.html