Zkw线段树 Link
Time: $O(\log N)$ with very low constant. The core innovation is the closed interval query [l, r] (inclusive) using two pointers.
Abstract The segment tree is a fundamental data structure for range queries and point updates. While recursive implementations are intuitive, they suffer from high constant factors due to function call overhead and conditional branching. This paper describes the zkw segment tree , a non‑recursive alternative introduced by Zhang Kunwei (zkw). By storing data in a perfect binary tree indexed from the bottom layer, it eliminates recursion entirely. The resulting implementation is shorter, faster, and particularly well‑suited for competitive programming and low‑latency systems. 1. Introduction A standard segment tree is usually built as an array tree[] of size about 4*N . Recursive functions traverse the tree to answer range sum/min/max queries or apply point updates. Despite its asymptotic $O(\log N)$ performance, recursion overhead and repeated bounds checking slow down execution. zkw线段树
int prefix(int r) r += N; int res = 0; while (r) if (!(r & 1)) res += tree[r]; r >>= 1; return res; Time: $O(\log N)$ with very low constant
Prefix sum [0, r] :
template<typename T> class ZkwSegTree int N; vector<T> tree; public: ZkwSegTree(int n, const vector<T>& init) N = 1; while (N < n) N <<= 1; tree.assign(2*N, 0); for (int i = 0; i < n; i++) tree[N+i] = init[i]; for (int i = N-1; i; i--) tree[i] = tree[2*i] + tree[2*i+1]; void update(int p, T val) p += N; tree[p] = val; while (p >>= 1) tree[p] = tree[2*p] + tree[2*p+1]; T query(int l, int r) // inclusive l += N, r += N; T res = 0; while (l <= r) if (l & 1) res += tree[l++]; if (!(r & 1)) res += tree[r--]; l >>= 1; r >>= 1; return res; ; int res = 0