segment tree questions code example

Example 1: segment tree

// General Segment Tree struct
// Original source: https://codeforces.com/blog/entry/18051

template<class T> struct SegTree {

    int size;
    T defVal;
    vector<T> tree;
    T (*op)(T, T);
    
    SegTree (int size, T defVal, T (*op)(T, T))
        : size(size), defVal(defVal), tree(vector<T>(2*size)), op(op) {}
    SegTree (vector<T> v, T defVal, T (*op)(T, T))
        : SegTree(v.size()/2, defVal, op) {
        for (int i = 0; i<size; ++i) {
            tree[i+size] = v[i];
        }
        build();
    }

    void build() {

        for (int i = size-1; i>0; --i) {
            tree[i] = op(tree[i<<1], tree[i<<1|1]);
        }

    }
    T query (int l, int r) {

        l += size, r += size+1;
        T res;
        for (res = defVal; l<r; l >>= 1, r >>= 1) {
            if (l&1) res = op(res, tree[l++]);
            if (r&1) res = op(res, tree[--r]);
        }
        return res;

    }
    void update (int i, T val) {

        i += size;
        for (tree[i] = val; i>1; i >>= 1) {
            tree[i>>1] = op(tree[i], tree[i^1]);
        }

    }

};

Example 2: segment tree

const int N = 1e5;  // limit for array size
int n;  // array size
int t[2 * N];

void build() {  // build the tree
  	for (int i = n - 1; i > 0; --i) t[i] = t[i<<1] + t[i<<1|1];
}

void modify(int p, int value) {  // set value at position p
  	for (t[p += n] = value; p > 1; p >>= 1) t[p>>1] = t[p] + t[p^1];
}

int query(int l, int r) {  // sum on interval [l, r)
    int res = 0;
    for (l += n, r += n; l < r; l >>= 1, r >>= 1) {
        if (l&1) res += t[l++];
        if (r&1) res += t[--r];
    }
    return res;
}

int main() {
	std::cin>>n;
    for (int i = 0; i < n; ++i) std::cin>>t[n+i];
    build();
    modify(0, 1);
    std::cout<<query(3, 11)<<'\n';
    return 0;
}

Example 3: Segment tree

void build(int node, int start, int end)
{
    if(start == end)
    {
        // Leaf node will have a single element
        tree[node] = A[start];
    }
    else
    {
        int mid = (start + end) / 2;
        // Recurse on the left child
        build(2*node, start, mid);
        // Recurse on the right child
        build(2*node+1, mid+1, end);
        // Internal node will have the sum of both of its children
        tree[node] = tree[2*node] + tree[2*node+1];
    }
}

Tags:

C Example