Conceiving Persistent Structure
I've been focusing on the core concept: a Persistent Segment Tree. I'm now clear on the necessity of range queries and how they drive the design. The goal is to create a data structure that permits access to past versions after modifications.
Refining Data Operations
I'm now zeroing in on the Build, Update, and Query operations. Each action requires precise handling to ensure version integrity. The challenge lies in efficiently incorporating changes within these operations, particularly with the introduction of new nodes for each update. I'm focusing on the structural differences from standard segment trees, such as the heap-based implementation, to accommodate persistence.
Detailing Memory Strategies
I'm presently considering the dynamic memory allocation requirements. I've concluded that a static array with an index counter will be the most efficient approach for node allocation, especially given performance constraints common to competitive programming. I'm fleshing out the specific implementation details, focusing on how node indices will be managed during Build and Update operations, to prevent memory leaks or inefficiencies.
Optimizing Node Interactions
I'm presently dissecting the Update operation. I'm focusing on node property modifications and how prev_node references work. Leaf node updates are straightforward, while internal node updates require careful allocation. My current approach prioritizes shared memory, retaining unchanged branches of the tree, creating new subtrees only where necessary, and recursively updating sum. I'm verifying the correctness of the splitting logic to maintain the integrity of range queries.
Codifying the Logic
I'm translating the conceptual structure into code, focusing on the build and update functions. The Node struct and the tree array are in place. Now I'm working on the recursion in the update function, ensuring it correctly creates new nodes when the path diverges and shares the unchanged branches of the tree. I'm especially focused on how the prev_id is used to facilitate versioning and memory efficiency. The roots array will be used to track the root node for each version.
Developing Multi-Language Support
I'm now expanding my scope to include a Python implementation. The C++ version is performant, but Python offers wider accessibility and clearer logic for those less comfortable with C++ memory management. I'm focusing on crafting a class structure and replacing pointer logic with object references and None checks for the Python version. This includes mapping array indexing correctly from 1-based (internal tree range representation) to the initial input.
Validating Array Bounds
I'm presently focusing on array size constraints. I've realized that the C++ array needs careful sizing due to the NlogN node creation. For an input of N=105, I need to account for approximately 2⋅10 nodes, which necessitates a larger array than I initially considered. I'm verifying the array dimensions to accommodate worst-case scenarios and prevent potential out-of-bounds errors during operations.
Here is a complete implementation of a Persistent Segment Tree supporting Point Updates and Range Sum Queries.
I have provided two implementations: C++ (highly optimized, standard for competitive programming/systems) and Python (object-oriented, optimized for readability).
Concept: Path Copying
In a standard segment tree, an update modifies a leaf and the internal nodes on the path to the root. In a persistent tree:
- When updating a value, we do not modify the existing nodes.
- We create a new node for the root of the new version.
- As we traverse down to the leaf, we create new nodes for the path that changes.
- For the branches that do not change, the new node simply points to the child of the previous version.
1. C++ Implementation
This uses a static array allocation strategy (Memory Pool) which is significantly faster than dynamic new pointers and prevents memory fragmentation.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Maximum limits
const int MAXN = 100005; // Max elements in array
const int MAX_LOG = 20; // Approx log2(MAXN)
// Memory Pool size: N log N updates + initial build.
// 40x is a safe upper bound for competitive programming contexts.
const int MAX_NODES = MAXN * 40;
struct Node {
long long val; // Sum of the range
int left; // Index of left child
int right; // Index of right child
} tree[MAX_NODES];
int node_cnt = 0; // Counter for allocated nodes
int roots[MAXN]; // Stores the root node index for each version
int input_arr[MAXN]; // Input data
// Function to allocate a new node
int new_node(long long val = 0) {
int id = ++node_cnt;
tree[id].val = val;
tree[id].left = 0;
tree[id].right = 0;
return id;
}
// 1. Build the initial tree (Version 0)
// tl = tree left limit, tr = tree right limit
int build(int tl, int tr) {
int node = new_node();
if (tl == tr) {
tree[node].val = input_arr[tl];
return node;
}
int tm = (tl + tr) / 2;
tree[node].left = build(tl, tm);
tree[node].right = build(tm + 1, tr);
// Pull up values
tree[node].val = tree[tree[node].left].val + tree[tree[node].right].val;
return node;
}
// 2. Update Point (Creates new version)
// Returns the index of the new node created
int update(int prev_node, int tl, int tr, int idx, int new_val) {
int node = new_node();
// Copy data from previous version's node (Path Copying)
tree[node].left = tree[prev_node].left;
tree[node].right = tree[prev_node].right;
tree[node].val = tree[prev_node].val;
if (tl == tr) {
tree[node].val = new_val;
return node;
}
int tm = (tl + tr) / 2;
if (idx <= tm) {
// If target is in the left child, create new left child, keep old right
tree[node].left = update(tree[prev_node].left, tl, tm, idx, new_val);
} else {
// If target is in right child, create new right child, keep old left
tree[node].right = update(tree[prev_node].right, tm + 1, tr, idx, new_val);
}
// Recalculate sum for the current new node
tree[node].val = tree[tree[node].left].val + tree[tree[node].right].val;
return node;
}
// 3. Range Query
long long query(int node, int tl, int tr, int l, int r) {
if (l > r) return 0; // Out of bounds
if (l == tl && r == tr) {
return tree[node].val;
}
int tm = (tl + tr) / 2;
// Standard segment tree query split
return query(tree[node].left, tl, tm, l, min(r, tm)) +
query(tree[node].right, tm + 1, tr, max(l, tm + 1), r);
}
int main() {
// Example Data
int n = 5;
int data[] = {0, 1, 2, 3, 4, 5}; // 1-based indexing for convenience
for(int i=1; i<=n; i++) input_arr[i] = data[i];
// --- Version 0 ---
roots[0] = build(1, n);
cout << "Version 0 (1-5): " << query(roots[0], 1, n, 1, 5) << endl; // Sum 1+2+3+4+5 = 15
// --- Create Version 1 ---
// Update index 3 (value 3) to value 10
roots[1] = update(roots[0], 1, n, 3, 10);
cout << "Version 1 (1-5): " << query(roots[1], 1, n, 1, 5) << endl; // Sum 1+2+10+4+5 = 22
// Check if Version 0 is still intact (Persistence check)
cout << "Version 0 Check: " << query(roots[0], 1, n, 1, 5) << endl; // Should still be 15
// --- Create Version 2 ---
// Update index 1 (value 1) to value 100 BASED ON Version 1
roots[2] = update(roots[1], 1, n, 1, 100);
cout << "Version 2 (1-5): " << query(roots[2], 1, n, 1, 5) << endl; // 100+2+10+4+5 = 121
// Query a sub-range on Version 1
cout << "Version 1 Range(2-4): " << query(roots[1], 1, n, 2, 4) << endl; // 2+10+4 = 16
return 0;
}
2. Python Implementation
This version creates classes. While slower than the C++ array approach, it is much easier to understand visually.
class Node:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class PersistentSegmentTree:
def __init__(self, arr):
"""
arr: List of numbers (0-indexed)
"""
self.n = len(arr)
self.roots = [] # To store the root node of each version
# Build Version 0
root_v0 = self._build(arr, 0, self.n - 1)
self.roots.append(root_v0)
def _build(self, arr, tl, tr):
node = Node()
if tl == tr:
node.val = arr[tl]
return node
mid = (tl + tr) // 2
node.left = self._build(arr, tl, mid)
node.right = self._build(arr, mid + 1, tr)
node.val = node.left.val + node.right.val
return node
def update(self, version, idx, new_val):
"""
Creates a new version based on 'version' where arr[idx] = new_val
Returns the version ID (index in roots list)
"""
prev_root = self.roots[version]
new_root = self._update_recursive(prev_root, 0, self.n - 1, idx, new_val)
self.roots.append(new_root)
return len(self.roots) - 1
def _update_recursive(self, prev_node, tl, tr, idx, new_val):
# Create new node and copy links/value from previous
node = Node(prev_node.val, prev_node.left, prev_node.right)
if tl == tr:
node.val = new_val
return node
mid = (tl + tr) // 2
if idx <= mid:
# Link to NEW left, keep OLD right
node.left = self._update_recursive(prev_node.left, tl, mid, idx, new_val)
else:
# Keep OLD left, link to NEW right
node.left = prev_node.left # explicit copy for clarity
node.right = self._update_recursive(prev_node.right, mid + 1, tr, idx, new_val)
node.val = node.left.val + node.right.val
return node
def query(self, version, l, r):
"""
Query sum from l to r in specific version
"""
return self._query_recursive(self.roots[version], 0, self.n - 1, l, r)
def _query_recursive(self, node, tl, tr, l, r):
if l > r:
return 0
if l == tl and r == tr:
return node.val
mid = (tl + tr) // 2
return (self._query_recursive(node.left, tl, mid, l, min(r, mid)) +
self._query_recursive(node.right, mid + 1, tr, max(l, mid+1), r))
# --- Usage ---
if __name__ == "__main__":
data = [1, 2, 3, 4, 5]
pst = PersistentSegmentTree(data)
print(f"Ver 0 (Full): {pst.query(0, 0, 4)}") # 15
# Update index 2 (val 3) -> 10. Creates Version 1.
pst.update(0, 2, 10)
print(f"Ver 1 (Full): {pst.query(1, 0, 4)}") # 1+2+10+4+5 = 22
# Verify Persistence (Ver 0 should not change)
print(f"Ver 0 Check: {pst.query(0, 0, 4)}") # 15
# Update index 0 -> 100 based on Version 1. Creates Version 2.
pst.update(1, 0, 100)
print(f"Ver 2 (Full): {pst.query(2, 0, 4)}") # 100+2+10+4+5 = 121
Complexity Analysis
Let N be the size of the array and M be the number of updates.
-
Time Complexity:
- Build: O(N)
- Update: O(logN) per update. We only visit nodes along one path from root to leaf.
- Query: O(logN) per query.
-
Space Complexity:
- Standard Segment Tree: (usually ).