Fenwick Tree Usage Patterns and Classic Problem Solutions
1. Single-Point Update with Prefix Sum Query
Maintain a sequence of n numbers. Support q operations: update an element to a new value, or compute the prefix sum up to a given index.
Construct a Fenwick tree over the index range [1, n]. On udpate, compute the delta and apply it to both the raw array and the tree.
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
template <typename T>
class Fenwick {
vector<T> bit;
int N, logN;
public:
Fenwick(int n) { init(n); }
void init(int n) {
N = n;
logN = 63 - __builtin_clzll(N);
bit.assign(N + 5, 0);
}
void add(int idx, T delta) {
for (; idx <= N; idx += idx & -idx) bit[idx] += delta;
}
T sum(int idx) {
T res = 0;
for (; idx; idx -= idx & -idx) res += bit[idx];
return res;
}
int lower_bound(T target) {
int pos = 0;
for (int i = logN; i >= 0; --i) {
int nxt = pos + (1 << i);
if (nxt <= N && bit[nxt] <= target) {
pos = nxt;
target -= bit[pos];
}
}
return pos;
}
};
int main() {
ios::sync_with_stdio(false); cin.tie(nullptr);
int n, q; cin >> n >> q;
vector<ll> a(n + 1);
Fenwick<ll> tree(n);
for (int i = 1; i <= n; ++i) {
cin >> a[i];
tree.add(i, a[i]);
}
while (q--) {
int type; cin >> type;
if (type == 1) {
int x; ll d; cin >> x >> d;
tree.add(x, d - a[x]);
a[x] = d;
} else {
int x; cin >> x;
cout << tree.sum(x) << '\n';
}
}
}
2. Range Add with Prefix Sum via Difference Arrays
2.1 Standard Range Add and Prefix Sum
All elements initialy zero. Support adding a value to a contiguous subarray and querying the prefix sum up to x modulo 2⁶⁴.
Express the prefix sum in terms of the difference array d. Two Fenwick trees are used: one storing d[i], another storing i·d[i].
#include <bits/stdc++.h>
using namespace std;
using u64 = unsigned long long;
template <typename T>
class RangeFenwick {
vector<T> D, ID;
int N;
public:
RangeFenwick(int n) { init(n); }
void init(int n) {
N = n;
D.assign(N + 5, 0);
ID.assign(N + 5, 0);
}
void add(int idx, T val) {
for (int i = idx; i <= N; i += i & -i) {
D[i] += val;
ID[i] += val * idx;
}
}
void range_add(int l, int r, T val) {
add(l, val);
add(r + 1, -val);
}
T prefix_sum(int x) {
T s = 0;
for (int i = x; i; i -= i & -i)
s += D[i] * (x + 1) - ID[i];
return s;
}
T range_sum(int l, int r) {
return prefix_sum(r) - prefix_sum(l - 1);
}
};
int main() {
ios::sync_with_stdio(false); cin.tie(nullptr);
int n, q; cin >> n >> q;
RangeFenwick<u64> tree(n);
while (q--) {
int t; cin >> t;
if (t == 1) {
int l, r; u64 d; cin >> l >> r >> d;
tree.range_add(l, r, d);
} else {
int x; cin >> x;
cout << tree.prefix_sum(x) << '\n';
}
}
}
2.2 Range Flip on Binary Strings
Given a binary string, choose a length k and repeatedly flip any length‑k segment. Find the maximal k such that the string can become all ones. Process the string left‑to‑right, flipping the first zero. XOR operations require adapting the difference formula using parity. Two Fenwick trees maintain d[i] and (i mod 2)·d[i].
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
template <typename T>
class XorRangeFenwick {
vector<T> A, B;
int N;
public:
XorRangeFenwick(int n) { init(n); }
void init(int n) {
N = n;
A.assign(N + 5, 0);
B.assign(N + 5, 0);
}
void add(int idx, T val) {
for (int i = idx; i <= N; i += i & -i) {
A[i] ^= val;
B[i] ^= val * (idx % 2);
}
}
void range_add(int l, int r, T val) {
add(l, val);
add(r + 1, val);
}
T prefix_xor(int x) {
T s = 0;
for (int i = x; i; i -= i & -i)
s ^= A[i] * ((x + 1) % 2) ^ B[i];
return s;
}
T point_query(int x) { return prefix_xor(x) ^ prefix_xor(x - 1); }
};
void solve() {
int n; cin >> n;
string s; cin >> s;
vector<int> a(n + 1);
for (int i = 1; i <= n; ++i) a[i] = s[i - 1] - '0';
auto possible = [&](int k) {
XorRangeFenwick<ll> ft(n);
for (int i = 1; i <= n; ++i) ft.range_add(i, i, a[i]);
for (int i = 1; i + k - 1 <= n; ++i)
if (!ft.point_query(i)) ft.range_add(i, i + k - 1, 1);
for (int i = 1; i <= n; ++i)
if (!ft.point_query(i)) return false;
return true;
};
for (int k = n; k; --k)
if (possible(k)) { cout << k << '\n'; return; }
}
int main() {
ios::sync_with_stdio(false); cin.tie(nullptr);
int t; cin >> t;
while (t--) solve();
}
2.3 Higher‑Order Arithmetic Progression Add
An array a is modified by adding an arithmetic sequence to a segment. Queries ask for the current value at a single index. Construct two systems of Fenwick trees: one for the original array using first‑order difference, and another for the zero‑initialized second‑order difference to handle the equal‑difference part.
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
template <typename T>
class Order1Fenwick {
vector<T> D1, D2;
int N;
public:
Order1Fenwick(int n) : N(n) {
D1.assign(N + 5, 0);
D2.assign(N + 5, 0);
}
void add(int idx, T delta) {
for (int i = idx; i <= N; i += i & -i) {
D1[i] += delta;
D2[i] += delta * idx;
}
}
void range_add(int l, int r, T delta) {
add(l, delta);
add(r + 1, -delta);
}
T prefix_sum(int x) {
T res = 0;
for (int i = x; i; i -= i & -i)
res += D1[i] * (x + 1) - D2[i];
return res;
}
};
template <typename T>
class Order2Fenwick {
vector<T> C1, C2, C3;
int N;
public:
Order2Fenwick(int n) : N(n) {
C1.assign(N + 5, 0);
C2.assign(N + 5, 0);
C3.assign(N + 5, 0);
}
void add(int idx, T delta) {
for (int i = idx; i <= N; i += i & -i) {
C1[i] += delta;
C2[i] += delta * idx;
C3[i] += delta * (idx * idx - 3 * idx) / 2;
}
}
void range_add(int l, int r, T delta) {
add(l, delta);
add(r + 1, -delta);
}
T prefix_sum(int x) {
T s = 0;
for (int i = x; i; i -= i & -i)
s += C1[i] * (x + 1) * (x + 2) / 2 - C2[i] * x + C3[i];
return s;
}
};
int main() {
ios::sync_with_stdio(false); cin.tie(nullptr);
int n, q; cin >> n >> q;
Order1Fenwick<ll> P(n);
Order2Fenwick<ll> Q(n);
vector<ll> a(n + 2);
for (int i = 1; i <= n; ++i) {
cin >> a[i];
P.range_add(i, i, a[i]);
}
while (q--) {
int typ; cin >> typ;
if (typ == 1) {
int l, r; ll K, D; cin >> l >> r >> K >> D;
P.range_add(l, r, K);
Q.range_add(l + 1, r, D);
P.range_add(r + 1, n, -D * (r - l));
} else {
int x; cin >> x;
ll ans = P.prefix_sum(x) - P.prefix_sum(x - 1) + Q.prefix_sum(x) - Q.prefix_sum(x - 1);
cout << ans << '\n';
}
}
}
3. Binary Lifting and Order Statistics
3.1 Find Largest Prefix Sum ≤ S
Maintain the array a and answer queries: after an update or query with value s, find the maximum index T such that the prefix sum up to T does not exceed s. Use the lower_bound method implemented via bit‑level binary lifting.
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
template <typename T>
class FenwickLB {
vector<T> bit;
int N, logN;
public:
FenwickLB(int n) { init(n); }
void init(int n) {
N = n + 1;
logN = 63 - __builtin_clzll(N);
bit.assign(N + 5, 0);
}
void add(int idx, T delta) {
for (; idx <= N; idx += idx & -idx) bit[idx] += delta;
}
int prefix_search(T target) {
int pos = 0;
for (int i = logN; i >= 0; --i) {
int nxt = pos + (1 << i);
if (nxt <= N && bit[nxt] <= target) {
pos = nxt;
target -= bit[pos];
}
}
return pos;
}
};
int main() {
ios::sync_with_stdio(false); cin.tie(nullptr);
int n, q; cin >> n >> q;
FenwickLB<ll> ft(n);
vector<ll> a(n + 1);
for (int i = 1; i <= n; ++i) {
cin >> a[i];
ft.add(i, a[i]);
}
while (q--) {
int typ; cin >> typ;
if (typ == 1) {
int x; ll d; cin >> x >> d;
ft.add(x, d - a[x]);
a[x] = d;
} else {
ll s; cin >> s;
int T = ft.prefix_search(s);
if (T > n) T = n;
cout << T << '\n';
}
}
}
3.2 Dynamic Median (k‑th Smallest)
Insert elements one by one and after each odd‑length prefix, output the median. Discretize the values. A Fenwick tree stores frequencies. The k‑th smallest is find(k-1)+1.
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
template <typename T>
class FenwickLB {
vector<T> bit;
int N, logN;
public:
FenwickLB(int n) {
N = n + 5;
logN = 63 - __builtin_clzll(N);
bit.assign(N, 0);
}
void add(int idx, T delta) {
for (; idx <= N; idx += idx & -idx) bit[idx] += delta;
}
int kth(T k) { // 1‑based
int pos = 0;
for (int i = logN; i >= 0; --i) {
int nxt = pos + (1 << i);
if (nxt <= N && bit[nxt] <= k) {
pos = nxt;
k -= bit[pos];
}
}
return pos + 1;
}
};
int main() {
ios::sync_with_stdio(false); cin.tie(nullptr);
int n; cin >> n;
vector<int> a(n);
vector<int> vals;
for (int i = 0; i < n; ++i) {
cin >> a[i];
vals.push_back(a[i]);
}
sort(vals.begin(), vals.end());
vals.erase(unique(vals.begin(), vals.end()), vals.end());
FenwickLB<int> ft(vals.size());
for (int i = 0; i < n; ++i) {
int idx = lower_bound(vals.begin(), vals.end(), a[i]) - vals.begin() + 1;
ft.add(idx, 1);
if (i % 2 == 0) {
int med_idx = ft.kth((i + 1) / 2);
cout << vals[med_idx - 1] << '\n';
}
}
}
4. 2D Prefix Partially Ordered Queries
4.1 Inversion Count (Reverse Pairs)
Count pairs (i, j) with i < j and a[i] > a[j]. Discretize a. Sweep from right to left, query count of values smaller than current, then insert current value.
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
template <typename T>
class Fenwick {
vector<T> bit;
int N;
public:
Fenwick(int n) : N(n) { bit.assign(N + 5, 0); }
void add(int idx, T delta = 1) {
for (; idx <= N; idx += idx & -idx) bit[idx] += delta;
}
T sum(int idx) {
T s = 0;
for (; idx; idx -= idx & -idx) s += bit[idx];
return s;
}
};
int main() {
ios::sync_with_stdio(false); cin.tie(nullptr);
int n; cin >> n;
vector<int> a(n), vals(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
vals[i] = a[i];
}
sort(vals.begin(), vals.end());
vals.erase(unique(vals.begin(), vals.end()), vals.end());
Fenwick<int> ft(vals.size());
ll ans = 0;
for (int i = n - 1; i >= 0; --i) {
int idx = lower_bound(vals.begin(), vals.end(), a[i]) - vals.begin() + 1;
ans += ft.sum(idx - 1);
ft.add(idx);
}
cout << ans << '\n';
}
4.2 Longest Increasing Subsequence with Transformed Values
Find the minimum changes to make a sequence strictly increasing. Transform a[i] to a[i] - i; the problem reduces to a longest non‑decreasing subsequence. Discretize the transformed values, then use a Fenwick tree storing maximum DP value.
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
template <typename T>
class MaxFenwick {
vector<T> bit;
int N;
public:
MaxFenwick(int n) : N(n) { bit.assign(N + 5, 0); }
void update(int idx, T val) {
for (; idx <= N; idx += idx & -idx) bit[idx] = max(bit[idx], val);
}
T query(int idx) {
T best = 0;
for (; idx; idx -= idx & -idx) best = max(best, bit[idx]);
return best;
}
};
int main() {
ios::sync_with_stdio(false); cin.tie(nullptr);
int t; cin >> t;
for (int tc = 1; tc <= t; ++tc) {
int n; cin >> n;
vector<ll> a(n), b(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
b[i] = a[i] + n + 1 - (i + 1);
}
vector<ll> vals(b);
sort(vals.begin(), vals.end());
vals.erase(unique(vals.begin(), vals.end()), vals.end());
MaxFenwick<ll> ft(vals.size());
ll best = 0;
for (int i = 0; i < n; ++i) {
int idx = lower_bound(vals.begin(), vals.end(), b[i]) - vals.begin() + 1;
ll dp = ft.query(idx) + 1;
best = max(best, dp);
ft.update(idx, dp);
}
cout << "Case #" << tc << ":\n" << n - best << '\n';
}
}
4.3 Maximum Sum Increasing Subsequence
Find the subsequence with strictly increasing values whose sum is maximal. DP state: dp[i] = a[i] + max{dp[j] : j < i, a[j] < a[i]}. Maintain a maximising Fenwick tree on value indices.
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
template <typename T>
class MaxFenwick {
vector<T> bit;
int N;
public:
MaxFenwick(int n) : N(n) { bit.assign(N + 5, 0); }
void update(int idx, T val) {
for (; idx <= N; idx += idx & -idx) bit[idx] = max(bit[idx], val);
}
T query(int idx) {
T best = 0;
for (; idx; idx -= idx & -idx) best = max(best, bit[idx]);
return best;
}
};
int main() {
ios::sync_with_stdio(false); cin.tie(nullptr);
int n; cin >> n;
vector<ll> a(n);
ll maxV = 0;
for (int i = 0; i < n; ++i) {
cin >> a[i];
maxV = max(maxV, a[i]);
}
MaxFenwick<ll> ft(maxV);
ll answer = 0;
for (int i = 0; i < n; ++i) {
ll best = ft.query(a[i] - 1) + a[i];
answer = max(answer, best);
ft.update(a[i], best);
}
cout << answer << '\n';
}
5. Offline Sweep‑Line and 2D Counting
5.1 2D Orthogonal Range Counting
Given n points and q axis‑aligned rectangles, count points inside each rectangle. Sweep vertically, discretize the x‑coordinates of points. For each rectangle, decompose into four corner queries with signs ±1 and process events sorted by y, then by priority.
#include <bits/stdc++.h>
using namespace std;
template <typename T>
class Fenwick {
vector<T> bit;
int N;
public:
Fenwick(int n) : N(n) { bit.assign(N + 5, 0); }
void add(int idx, T delta) {
for (; idx <= N; idx += idx & -idx) bit[idx] += delta;
}
T sum(int idx) {
T s = 0;
for (; idx; idx -= idx & -idx) s += bit[idx];
return s;
}
};
int main() {
ios::sync_with_stdio(false); cin.tie(nullptr);
int n, q; cin >> n >> q;
vector<array<int, 4>> events; // y, priority, x, id
vector<int> xs;
for (int i = 0; i < n; ++i) {
int x, y; cin >> x >> y;
xs.push_back(x);
events.push_back({y, 0, x, 0});
}
for (int i = 1; i <= q; ++i) {
int xl, xr, yl, yr; cin >> xl >> xr >> yl >> yr;
events.push_back({yr, 1, xr, i});
events.push_back({yl - 1, 1, xl - 1, i});
events.push_back({yr, 2, xl - 1, i});
events.push_back({yl - 1, 2, xr, i});
}
sort(xs.begin(), xs.end());
xs.erase(unique(xs.begin(), xs.end()), xs.end());
sort(events.begin(), events.end());
Fenwick<int> ft(xs.size());
vector<long long> ans(q + 1);
for (auto &ev : events) {
int y = ev[0], prio = ev[1], x = ev[2], id = ev[3];
if (prio == 0) {
int px = lower_bound(xs.begin(), xs.end(), x) - xs.begin() + 1;
ft.add(px, 1);
} else {
int px = upper_bound(xs.begin(), xs.end(), x) - xs.begin();
int cnt = ft.sum(px);
if (prio == 1) ans[id] += cnt;
else ans[id] -= cnt;
}
}
for (int i = 1; i <= q; ++i) cout << ans[i] << '\n';
}
5.2 Sum of Distinct Elements in Intervals
Given an array a and queries [l, r], compute the sum of distinct values in the interval. Two common solutions:
Method 1 (offline sweep): For each index i, let pre[i] be the previous occurrence of a[i]. A value contributes iff pre[i] < l. Treat pre[i] as y‑coordinate and i as x‑coordinate. Decompose query into two rectangles and sweep.
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
template <typename T>
class Fenwick {
vector<T> bit;
int N;
public:
Fenwick(int n) : N(n) { bit.assign(N + 5, 0); }
void add(int idx, T delta) {
for (; idx <= N; idx += idx & -idx) bit[idx] += delta;
}
T sum(int idx) {
T s = 0;
for (; idx; idx -= idx & -idx) s += bit[idx];
return s;
}
};
int main() {
ios::sync_with_stdio(false); cin.tie(nullptr);
int n, q; cin >> n >> q;
vector<int> a(n + 1), last(n + 1), pre(n + 1);
vector<array<int, 4>> events;
for (int i = 1; i <= n; ++i) {
cin >> a[i];
pre[i] = last[a[i]];
last[a[i]] = i;
events.push_back({pre[i], 0, i, 0});
}
for (int i = 1; i <= q; ++i) {
int l, r; cin >> l >> r;
events.push_back({l - 1, 1, r, i});
events.push_back({l - 1, 2, l - 1, i});
}
sort(events.begin(), events.end());
Fenwick<ll> ft(n);
vector<ll> ans(q + 1);
for (auto &ev : events) {
if (ev[1] == 0) ft.add(ev[2], a[ev[2]]);
else if (ev[1] == 1) ans[ev[3]] += ft.sum(ev[2]);
else ans[ev[3]] -= ft.sum(ev[2]);
}
for (int i = 1; i <= q; ++i) cout << ans[i] << '\n';
}
Method 2 (prefix maintenance): Iterate r from 1 to n. Maintain an array ansL for each possible left endpoint. Adding a[r] affects left endpoints in [pre[r]+1, r]. Use a range‑update Fenwick tree and answer queries offline when r matches the query boundary.
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
template <typename T>
class Fenwick {
vector<T> bit;
int N;
public:
Fenwick(int n) : N(n) { bit.assign(N + 5, 0); }
void add(int idx, T delta) {
for (; idx <= N; idx += idx & -idx) bit[idx] += delta;
}
T sum(int idx) {
T s = 0;
for (; idx; idx -= idx & -idx) s += bit[idx];
return s;
}
};
int main() {
ios::sync_with_stdio(false); cin.tie(nullptr);
int n, q; cin >> n >> q;
vector<int> a(n + 1), last(n + 1);
for (int i = 1; i <= n; ++i) cin >> a[i];
vector<vector<array<int,2>>> queries(n + 1);
for (int i = 1; i <= q; ++i) {
int l, r; cin >> l >> r;
queries[r].push_back({l, i});
}
Fenwick<ll> ft(n);
vector<ll> ans(q + 1);
for (int r = 1; r <= n; ++r) {
int prv = last[a[r]];
ft.add(prv + 1, a[r]);
ft.add(r + 1, -a[r]);
last[a[r]] = r;
for (auto &[l, id] : queries[r]) ans[id] = ft.sum(l);
}
for (int i = 1; i <= q; ++i) cout << ans[i] << '\n';
}
6. Multidimensional Fenwick Trees
6.1 2D Point Update and Prefix Query
Maintain n×m matrix. Supports point update and 2D prefix sum query. Nested loops over lowbit paths.
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
template <typename T>
class Fenwick2D {
vector<vector<T>> bit;
int R, C;
public:
Fenwick2D(int r, int c) : R(r + 1), C(c + 1) {
bit.assign(R + 5, vector<T>(C + 5, 0));
}
void add(int x, int y, T delta) {
for (int i = x; i <= R; i += i & -i)
for (int j = y; j <= C; j += j & -j)
bit[i][j] += delta;
}
T sum(int x, int y) {
T s = 0;
for (int i = x; i; i -= i & -i)
for (int j = y; j; j -= j & -j)
s += bit[i][j];
return s;
}
};
int main() {
ios::sync_with_stdio(false); cin.tie(nullptr);
int n, m, q; cin >> n >> m >> q;
Fenwick2D<ll> ft(n, m);
vector<vector<ll>> a(n + 1, vector<ll>(m + 1));
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= m; ++j) {
cin >> a[i][j];
ft.add(i, j, a[i][j]);
}
while (q--) {
int t; cin >> t;
if (t == 1) {
int x, y; ll d; cin >> x >> y >> d;
ft.add(x, y, d - a[x][y]);
a[x][y] = d;
} else {
int x, y; cin >> x >> y;
cout << ft.sum(x, y) << '\n';
}
}
}
6.2 2D Range Add and Renge Sum
Support rectangle addition and rectangle sum query. Derive the formula using four 2D Fenwick trees storing d[i][j], i·d[i][j], j·d[i][j], and i·j·d[i][j].
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
template <typename T>
class RangeFenwick2D {
vector<vector<T>> A, B, C, D;
int R, C;
public:
RangeFenwick2D(int r, int c) : R(r + 5), C(c + 5) {
A.assign(R, vector<T>(C, 0));
B.assign(R, vector<T>(C, 0));
C.assign(R, vector<T>(C, 0));
D.assign(R, vector<T>(C, 0));
}
void add(int x, int y, T val) {
for (int i = x; i < R; i += i & -i)
for (int j = y; j < C; j += j & -j) {
A[i][j] += val;
B[i][j] += val * y;
C[i][j] += val * x;
D[i][j] += val * x * y;
}
}
void rect_add(int xl, int yl, int xr, int yr, T val) {
add(xl, yl, val);
add(xl, yr + 1, -val);
add(xr + 1, yl, -val);
add(xr + 1, yr + 1, val);
}
T query(int x, int y) {
T s = 0;
for (int i = x; i; i -= i & -i)
for (int j = y; j; j -= j & -j)
s += A[i][j] * (x + 1) * (y + 1) - B[i][j] * (x + 1) - C[i][j] * (y + 1) + D[i][j];
return s;
}
T rect_sum(int xl, int yl, int xr, int yr) {
return query(xr, yr) - query(xl - 1, yr) - query(xr, yl - 1) + query(xl - 1, yl - 1);
}
};
int main() {
ios::sync_with_stdio(false); cin.tie(nullptr);
int n, m; scanf("%d%d", &n, &m);
RangeFenwick2D<ll> ft(n, m);
int typ;
while (scanf("%d", &typ) != EOF) {
if (typ == 1) {
int a, b, c, d, x; scanf("%d%d%d%d%d", &a, &b, &c, &d, &x);
ft.rect_add(a, b, c, d, x);
} else {
int a, b, c, d; scanf("%d%d%d%d", &a, &b, &c, &d);
printf("%lld\n", ft.rect_sum(a, b, c, d));
}
}
}