线段树模板

· · 科技·工程

#include <bits/stdc++.h>
using namespace std;

#define ls(x) ((x) << 1)
#define rs(x) ((x) << 1 | 1)
#define mid ((l + r) >> 1)

template<class Info, class Tag>
struct LazySegmentTree {
    int n;
    vector<Info> info;
    vector<Tag> tag;

    LazySegmentTree() : n(0) {}

    LazySegmentTree(int n_, const Info &v_ = Info()) {
        init(n_, v_);
    }

    template<class T>
    LazySegmentTree(const vector<T> &init_) {
        init(init_);
    }

    void init(int n_, const Info &v_ = Info()) {
        init(vector<Info>(n_ + 1, v_));
    }

    template<class T>
    void init(const vector<T> &init_) {
        n = (int)init_.size() - 1;
        int sz = 4 * max(1, n) + 10;
        info.assign(sz, Info());
        tag.assign(sz, Tag());
        if (n >= 1) build(1, 1, n, init_);
    }

    template<class T>
    void build(int u, int l, int r, const vector<T> &a) {
        if (l == r) {
            info[u] = a[l];
            return;
        }
        build(ls(u), l, mid, a);
        build(rs(u), mid + 1, r, a);
        pushup(u);
    }

    void pushup(int u) {
        info[u] = info[ls(u)] + info[rs(u)];
    }

    void apply(int u, const Tag &v) {
        info[u].apply(v);
        tag[u].apply(v);
    }

    void pushdown(int u) {
        apply(ls(u), tag[u]);
        apply(rs(u), tag[u]);
        tag[u] = Tag();
    }

    void modify(int u, int l, int r, int x, const Info &v) {
        if (l == r) {
            info[u] = v;
            return;
        }
        pushdown(u);
        if (x <= mid) modify(ls(u), l, mid, x, v);
        else modify(rs(u), mid + 1, r, x, v);
        pushup(u);
    }

    void modify(int x, const Info &v) {
        modify(1, 1, n, x, v);
    }

    Info rangeQuery(int u, int l, int r, int ql, int qr) {
        if (l > qr || r < ql) return Info();
        if (ql <= l && r <= qr) return info[u];

        pushdown(u);
        return rangeQuery(ls(u), l, mid, ql, qr) +
               rangeQuery(rs(u), mid + 1, r, ql, qr);
    }

    Info rangeQuery(int l, int r) {
        return rangeQuery(1, 1, n, l, r);
    }

    // 区间修改
    void rangeApply(int u, int l, int r, int ql, int qr, const Tag &v) {
        if (r < ql || qr < l) return;
        if (ql <= l && r <= qr) {
            apply(u, v);
            return;
        }

        pushdown(u);
        rangeApply(ls(u), l, mid, ql, qr, v);
        rangeApply(rs(u), mid + 1, r, ql, qr, v);
        pushup(u);
    }

    void rangeApply(int l, int r, const Tag &v) {
        rangeApply(1, 1, n, l, r, v);
    }
};