templates/fenwick-tree-range.cpp
compilable
$cat templates/fenwick-tree-range
Fenwick Tree Range
Fenwick tree supporting both range add and range sum queries using two BITs.
#fenwick#bit#range-add#range-sum
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_code/
cpp
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int MAXN = 2e5 + 5;
ll mul[MAXN], add[MAXN];
int n;
void bitAdd(int i, ll m, ll c) {
for (; i <= n; i += i & -i) {
mul[i] += m;
add[i] += c;
}
}
void rangeAdd(int l, int r, ll v) {
bitAdd(l, v, -v * (l - 1));
bitAdd(r + 1, -v, v * r);
}
ll prefSum(int i) {
ll s = 0;
int pos = i;
for (; i > 0; i -= i & -i)
s += pos * mul[i] + add[i];
return s;
}
ll query(int l, int r) {
return prefSum(r) - prefSum(l - 1);
}31 linesutf-8
$cat explanation_notes.md
notes_viewer --renderedmarkdown (math enabled)
Fenwick Tree with Range Updates
Supports range add and range sum simultaneously using two BITs, built on the difference array concept.
Key Identity
If is the difference array, then:
Two BIT arrays (mul and add) maintain these two components.
Operations
rangeAdd(l, r, v) — add to all elements in query(l, r) — sum of elements in