Implementing a Persistent Segment Tree
I’m planning to create a persistent segment tree to handle range queries and updates. The user hasn’t specified the programming dialect, so I’ll write a general library-like class with clear comments. It’s vital to explain the concept of persistence, including the time complexity of O(log n) for each query/update and worst-case memory usage of O(n log n). I should also mention that the tree can be adapted for min, max, or GCD operations. I’ll focus on clarity without unnecessary details or emojis.I'm focusing on making sure the code compiles correctly. I'll craft some C++ code to meet the user's requirements. Checking for compilation errors is crucial since they can be a real pain to troubleshoot later. My goal is to write clean, efficient code that integrates well with other parts of the project. I want to create an example that showcases how to handle possible errors and make it easy for the user to understand and work with.Implementing a Persistent Segment Tree
I'm outlining the steps to create a Persistent Segment Tree in C++. I have a class structure with a nested Node that holds the value and pointers to left and right child nodes. I’ll build the tree, updating and querying it effectively. The build function initializes nodes to store values from an input vector, while the update function allows modifications to specific nodes by maintaining version control. The query function retrieves sums within a given range efficiently. I’ll ensure the code is clear and easy to follow, focusing on proper structure.I'm wrapping up the Persistent Segment Tree implementation. The query function sums values efficiently within a range, utilizing the tree's structure. The constructor initializes the segment tree with an input vector, creating roots for each version. The new_version method updates a specific position and returns a new tree version. I’ll make sure to demonstrate this in the main function. It’s crucial to note that the class uses 0-indexing while versions reference from 0 to k. I'll include appropriate headers for portability, even though <bits/stdc++.h> is common in competitive programming.I'm crafting a minimal main function for demonstrating the Persistent Segment Tree. I’ll set it up with basic input/output functionality, allowing users to input the size of the array and the number of queries. The loop will handle two types of operations: creating a new version of the tree and querying the sum over a range. While printing the new version index is optional, I think it’s useful for demonstration purposes. However, I’ll focus on presenting the class and its functionality clearly, ensuring that the explanation remains straightforward and direct. Below is a clean C++ implementation of a persistent segment tree that supports:
- Range sum query on any version
- Point update that creates a new version (older versions stay unchanged)
You can easily change the operation from sum to min/max/etc.
Core idea
Each update creates a new root node and copies only the nodes on the path from root to the updated leaf. All other nodes are shared between versions.
Complexities:
- Update:
O(log n) time, O(log n) new nodes
- Query:
O(log n) time
- Memory:
O((n + #updates) * log n) nodes in the worst case
Implementation (C++)
#include <bits/stdc++.h>
using namespace std;
// Persistent segment tree for range sum, point assign updates.
struct PersistentSegTree {
struct Node {
long long val; // aggregate (sum over the segment)
int left, right; // indices of children in 'st'
Node(long long v = 0, int l = 0, int r = 0) : val(v), left(l), right(r) {}
};
int n;
vector<Node> st; // all nodes from all versions
vector<int> roots; // root index for each version
// Build initial tree from array a[l..r]
int build(int l, int r, const vector<long long> &a) {
int node = (int)st.size();
st.emplace_back();
if (l == r) {
st[node].val = a[l];
return node;
}
int mid = (l + r) / 2;
int leftChild = build(l, mid, a);
int rightChild = build(mid + 1, r, a);
st[node].left = leftChild;
st[node].right = rightChild;
st[node].val = st[leftChild].val + st[rightChild].val;
return node;
}
// Create a new node version by updating position 'pos' to 'value'
int update(int prevNode, int l, int r, int pos, long long value) {
int node = (int)st.size();
st.push_back(st[prevNode]); // copy previous node
if (l == r) {
st[node].val = value;
return node;
}
int mid = (l + r) / 2;
if (pos <= mid) {
int newLeft = update(st[prevNode].left, l, mid, pos, value);
st[node].left = newLeft;
} else {
int newRight = update(st[prevNode].right, mid + 1, r, pos, value);
st[node].right = newRight;
}
st[node].val = st[st[node].left].val + st[st[node].right].val;
return node;
}
// Range sum query on a particular version
long long query(int node, int l, int r, int ql, int qr) const {
if (qr < l || r < ql) return 0; // no overlap
if (ql <= l && r <= qr) return st[node].val; // full overlap
int mid = (l + r) / 2;
return query(st[node].left, l, mid, ql, qr)
+ query(st[node].right, mid + 1, r, ql, qr);
}
// Constructor: builds version 0 from array a[0..n-1]
explicit PersistentSegTree(const vector<long long> &a) {
n = (int)a.size();
st.reserve(n * 40); // heuristic, not mandatory
st.push_back(Node()); // dummy node at index 0 (unused root)
int root0 = build(0, n - 1, a);
roots.push_back(root0); // version 0
}
// Create a new version from 'baseVersion' by setting a[pos] = value
// Returns index of new version.
int new_version(int baseVersion, int pos, long long value) {
int baseRoot = roots[baseVersion];
int newRoot = update(baseRoot, 0, n - 1, pos, value);
roots.push_back(newRoot);
return (int)roots.size() - 1;
}
// Range sum query [l, r] on given version (0-based indices)
long long range_query(int version, int l, int r) const {
return query(roots[version], 0, n - 1, l, r);
}
};
// Example usage
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
// Initial array
vector<long long> a = {1, 2, 3, 4, 5};
PersistentSegTree pst(a);
// version 0: [1, 2, 3, 4, 5]
cout << "v0 sum[0..4] = " << pst.range_query(0, 0, 4) << "\n"; // 15
// Create version 1 from version 0 with a[2] = 10
int v1 = pst.new_version(0, 2, 10); // now v1: [1, 2, 10, 4, 5]
cout << "v1 sum[0..4] = " << pst.range_query(v1, 0, 4) << "\n"; // 22
cout << "v0 sum[0..4] = " << pst.range_query(0, 0, 4) << "\n"; // still 15
// Create version 2 from version 1 with a[0] = 7
int v2 = pst.new_version(v1, 0, 7); // v2: [7, 2, 10, 4, 5]
cout << "v2 sum[1..3] = " << pst.range_query(v2, 1, 3) << "\n"; // 2 + 10 + 4 = 16
return 0;
}
To adapt this:
- For a different operation (e.g.,
min), replace val and the combination + with min (and identity with +∞).
- For large constraints, ensure
reserve is large enough or let vector grow automatically.