模板 - 数据结构 - 线段树(单点修改)

这里是以区间最大值为例,要修改成其他的运算,注意修改每个函数的运算以及query中返回的无关值

这里的区间最大值设置的最小元素为-1(在query中表示与当前区间不相交的区间的结果)。

注意因为调用的方式传入l与r是(1,n),所以这个线段树(包括a)其实是从1开始计数的。

最后,小心爆MAXM

const int MAXM=200000;
int a[MAXM+5],st[(MAXM<<2)+5];
 
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);
        st[o]=max(st[o<<1],st[o<<1|1]);
    }
}
 
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);
        st[o]=max(st[o<<1],st[o<<1|1]);
    }
}
 
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);
}

猜你喜欢

转载自www.cnblogs.com/Yinku/p/10318874.html