DSA · Competitive Programmer · Pattern 4 of 9
Segment Tree & Fenwick Tree
13 problems.
Your progress0%
- 1st Visit
- 0/13
- 2nd Visit
- 0/13
- Revise
- 0/13
About this pattern
Range-query structures answer questions about subarrays while the array keeps changing. A Fenwick tree, or binary indexed tree, supports point updates and prefix sums in O(log n) with very little code, and also counts inversions or smaller elements once values are compressed to ranks. A segment tree is more general: each node stores an aggregate of its range, such as a sum, a minimum or a small struct, and any associative merge works. Lazy propagation extends it to range updates. Signals: many range queries mixed with updates, n and q around 2 * 10^5, or counting pairs that satisfy an order condition. Every operation costs O(log n).
struct Fenwick { // 1-indexed point add, prefix sum
int n; vector<long long> t;
Fenwick(int n) : n(n), t(n + 1, 0) {}
void add(int i, long long v) { for (; i <= n; i += i & -i) t[i] += v; }
long long sum(int i) { long long s = 0; for (; i > 0; i -= i & -i) s += t[i]; return s; }
};
struct SegTree { // 0-indexed point set, minimum on [l, r)
int n; vector<long long> t;
SegTree(int n) : n(n), t(2 * n, LLONG_MAX) {}
void set(int i, long long v) { for (t[i += n] = v; i > 1; i >>= 1) t[i >> 1] = min(t[i], t[i ^ 1]); }
long long query(int l, int r, long long res = LLONG_MAX) {
for (l += n, r += n; l < r; l >>= 1, r >>= 1) {
if (l & 1) res = min(res, t[l++]);
if (r & 1) res = min(res, t[--r]);
}
return res;
}
};