what is a segment tree code example
Example 1: segment tree
const int N = 1e5;
int n;
int t[2 * N];
void build() {
for (int i = n - 1; i > 0; --i) t[i] = t[i<<1] + t[i<<1|1];
}
void modify(int p, int value) {
for (t[p += n] = value; p > 1; p >>= 1) t[p>>1] = t[p] + t[p^1];
}
int query(int l, int 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 2: Segment tree
void build(int node, int start, int end)
{
if(start == end)
{
tree[node] = A[start];
}
else
{
int mid = (start + end) / 2;
build(2*node, start, mid);
build(2*node+1, mid+1, end);
tree[node] = tree[2*node] + tree[2*node+1];
}
}