Jul 11, 2024
build(a, v, tl, tr) {
if tl == tr {
t[v] = a[tl];
} else {
tm = (tl + tr)/2;
build(a, 2*v, tl, tm);
build(a, 2*v+1, tm+1, tr);
t[v] = t[2*v] + t[2*v+1];
}
}
query(v, tl, tr, l, r) {
if l > r {
return 0; // Identity element for sum
}
if l == tl && r == tr {
return t[v];
}
tm = (tl + tr) / 2;
return query(2*v, tl, tm, l, min(r, tm)) + query(2*v+1, tm+1, tr, max(l, tm+1), r);
}
update(v, tl, tr, pos, new_val) {
if tl == tr {
t[v] = new_val;
} else {
tm = (tl + tr) / 2;
if pos <= tm
update(2*v, tl, tm, pos, new_val);
else
update(2*v+1, tm+1, tr, pos, new_val);
t[v] = t[2*v] + t[2*v+1];
}
}
push(v) {
if lazy[v] != 0 {
t[2*v] += lazy[v];
lazy[2*v] += lazy[v];
t[2*v+1] += lazy[v];
lazy[2*v+1] += lazy[v];
lazy[v] = 0;
}
}
updateRange(v, tl, tr, l, r, addend) {
if l > r return;
if l == tl && tr == r {
t[v] += addend;
lazy[v] += addend;
} else {
push(v); // Push pending updates
tm = (tl + tr) / 2;
updateRange(2*v, tl, tm, l, min(r, tm), addend);
updateRange(2*v+1, tm+1, tr, max(l, tm+1), r, addend);
t[v] = t[2*v] + t[2*v+1];
}
}