Segment Tree
Segment Tree is a data structure that answers queries of a range efficiently, while being able to be modified.
Given the array A with N elements find the sum of all elements from Ai to Aj.
Each of the Q query consists of 3 integers.
If the first integer is 1, the query will continue with i and j. Print the sum of all elements from Ai to Aj.
If the first integer is 2, the query will continue with U and X. Replace the element at AU with X.Input:
N Q
A1 A2 ... AN1 i j
or
2 U X
#include<iostream>
#include<vector>
using namespace std;
vector<int> segTree, a;
void build(int idx, int l, int r) {
if (l == r) {
return segTree[idx] = a[l]; // or a[r]
}
int mid = (l + r) / 2;
build(2 * idx, l, mid);
build(2 * idx + 1, mid + 1, r);
segTree[idx] = segTree[2 * idx] + segTree[2 * idx + 1];
}
void update(int idx, int l, int r, int u, int x) {
if (l == r) {
segTree[idx] = x;
return;
}
int mid = (l + r) / 2;
if (x <= mid) update(2 * idx, l, mid, u, x);
else update(2 * idx + 1, mid + 1, r, u, x);
segTree[idx] = segTree[2 * idx] + segTree[2 * idx + 1];
}
int query(int idx, int l, int r, int x, int y) {
if (l <= x && y <= r) {
return segTree[idx];
} else if (y <= l || x >= r) {
return 0;
}
int mid = (l + r) / 2;
return query(2 * idx, l, mid, x, y) + query(2 * idx + 1, mid + 1, r, x, y);
}
int main() {
int n, q; cin >> n >> q;
for (int i = 0; i < n; i++) cin >> a[i];
segTree = vector<int>(n);
build(1, 0, n-1);
for (int i = 0; i < q; i++) {
int type, x, y; cin >> type >> x >> y;
if (type == 1) {
cout << query(1, 0, n-1, x, y);
} else {
update(1, 0, n-1, x, y);
}
}
}