线段树模板

贴一个自己实现线段树单点修改,区间查询,区间修改的模板


struct Node{
    int l, r;
    int sum, minn, maxx;     //特征值
    int lazy;
}tree[maxn<<2];              //开四倍空间
int num[maxn];               //数值数组

void build(int i, int l, int r){
    tree[i].l = l;
    tree[i].r = r;
    if(l == r){
        tree[i].sum = num[l];
        tree[i].minn = num[l];
        tree[i].maxx = num[l];
        tree[i].lazy = 0;
        return ;
    }

    int mid = (l+r)>>1;
    build(i<<1, l, mid);
    build(i<<1|1, mid+1, r);    //子树建树后更新特征值
    tree[i].sum = tree[i<<1].sum + tree[i<<1|1].sum;
    tree[i].maxx = max(tree[i<<1].maxx, tree[i<<1|1].maxx);
    tree[i].minn = min(tree[i<<1].minn, tree[i<<1|1].minn);
    tree[i].lazy = 0;
    return ;
}

void push_down(int i){ //以lazy表示区间加为例更改特征值
    if(tree[i].lazy){
        tree[i<<1].sum  += tree[i].lazy * (tree[i<<1].r-tree[i<<1].l+1);
        tree[i<<1].maxx += tree[i].lazy;
        tree[i<<1].minn += tree[i].lazy;
        tree[i<<1|1].sum  += tree[i].lazy * (tree[i<<1|1].r-tree[i<<1|1].l+1);
        tree[i<<1|1].maxx += tree[i].lazy;
        tree[i<<1|1].minn += tree[i].lazy;

        tree[i<<1].lazy += tree[i].lazy;
        tree[i<<1|1].lazy += tree[i].lazy;
        tree[i].lazy = 0;
    }
}

void addx(int i, int x, int k){  // num[x] += k
    tree[i].sum += k;
    if(tree[i].l == tree[i].r) return ;

    int mid = (tree[i].l+tree[i].r)>>1;
    if(x <= mid) addx(i<<1, x, k);
    else addx(i<<1|1, x, k);

    /** sum可以在下放前更新, maxx, minn 需要递归更新*/
    tree[i].maxx = max(tree[i<<1].maxx, tree[i<<1|1].maxx);
    tree[i].minn = min(tree[i<<1].minn, tree[i<<1|1].minn);
}

void addlr(int i, int l, int r, int k){  // num[l~r] += k
    if(tree[i].l==l && tree[i].r==r){
        tree[i].sum  += k*(tree[i].r-tree[i].l+1);
        tree[i].maxx += k;
        tree[i].minn -= k;
        tree[i].lazy += k;
        return ;
    }
    push_down(i);
    int mid = (tree[i].l+tree[i].r)>>1;
    if(mid >= r)
        addlr(i<<1, l, r, k);
    else if(mid < l)
        addlr(i<<1|1, l, r, k);
    else {
        addlr(i<<1, l, mid, k);
        addlr(i<<1|1, mid+1, r, k);
    }
    tree[i].sum = tree[i<<1].sum + tree[i<<1|1].sum;
    tree[i].maxx = max(tree[i<<1].maxx, tree[i<<1|1].maxx);
    tree[i].minn = min(tree[i<<1].minn, tree[i<<1|1].minn);
}

int query(int i, int l, int r){  //以sum为例
    if(tree[i].l==l && tree[i].r==r)
        return tree[i].sum;

    push_down(i);

    int mid = (tree[i].l+tree[i].r)>>1;
    if(mid >= r)
        return query(i<<1, l, r);
    else if(mid < l)
        return query(i<<1|1, l, r);
    else
        return query(i<<1, l, mid) + query(i<<1|1, mid+1, r);
}

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ShadowGhostH/article/details/81591957
个人分类: 模板 数据结构
上一篇NENU SUMMER TRAINING #3 (题解)
下一篇Codeforces Round #FF (Div. 1) C (Segment_Tree)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭