Implementing fully persistent segment tree for k-th smallest queries
The plan is to implement a persistent segment tree that clones nodes along update paths without modifying existing nodes, storing a separate root per prefix of the input array after coordinate compression. Queries use two roots to find the k-th smallest element in a subrange by comparing counts. I'll provide complete C++ code with comments demonstrating this approach.
A “persistent” segment tree never overwrites an existing node, it allocates a new node for each segment you touch on an update and lets all untouched subtrees be shared with the previous version. That way every historical version of the tree remains usable for queries.
For k‑th–smallest queries on subarrays you don’t even need dynamic updates: you build version i of the tree as the frequency table of the prefix a[1..i]. Then the multiset of values in a[l..r] is just the difference of version r and version l−1, and you can walk the two trees in parallel to select the k‑th element.
Here is a complete C++11 implementation. Values are coordinate–compressed to [1..m], root[i] points to the root node for prefix a[1..i], and kth(u,v,k) walks down using the frequency difference between version v and version u:
#include <bits/stdc++.h>
using namespace std;
struct Node {
int left, right;
int sum;
Node() : left(0), right(0), sum(0) {}
};
struct PersistentSegTree {
vector<Node> seg;
vector<int> root;
int n; // size of the value domain [1..n]
PersistentSegTree(int n_) : n(n_) {
seg.reserve(1); // will grow as needed
seg.push_back(Node()); // node 0 = null node with sum 0
}
// Create a new version by inserting +1 at position pos in prev version
int update(int prev, int l, int r, int pos) {
int cur = (int)seg.size();
seg.push_back(seg[prev]); // clone previous node
seg[cur].sum += 1;
if (l != r) {
int mid = (l + r) >> 1;
if (pos <= mid) {
int newLeft = update(seg[prev].left, l, mid, pos);
seg[cur].left = newLeft;
} else {
int newRight = update(seg[prev].right, mid + 1, r, pos);
seg[cur].right = newRight;
}
}
return cur;
}
// Query k-th smallest in the multiset represented by version v minus version u
int kth(int u, int v, int l, int r, int k) const {
if (l == r) return l;
int cntLeft = seg[seg[v].left].sum - seg[seg[u].left].sum;
int mid = (l + r) >> 1;
if (k <= cntLeft) {
return kth(seg[u].left, seg[v].left, l, mid, k);
} else {
return kth(seg[u].right, seg[v].right, mid + 1, r, k - cntLeft);
}
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, q;
if (!(cin >> n >> q)) return 0;
vector<int> a(n);
vector<int> all;
all.reserve(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
all.push_back(a[i]);
}
// coordinate compression
sort(all.begin(), all.end());
all.erase(unique(all.begin(), all.end()), all.end());
int m = (int)all.size();
vector<int> comp(n);
for (int i = 0; i < n; ++i) {
comp[i] = int(lower_bound(all.begin(), all.end(), a[i]) - all.begin()) + 1; // 1-based
}
PersistentSegTree pst(m);
pst.root.resize(n + 1);
pst.root[0] = 0; // empty tree
for (int i = 1; i <= n; ++i) {
pst.root[i] = pst.update(pst.root[i - 1], 1, m, comp[i - 1]);
}
while (q--) {
int l, r, k;
cin >> l >> r >> k;
// 1-based indices assumed for l and r
int idx = pst.kth(pst.root[l - 1], pst.root[r], 1, m, k);
cout << all[idx - 1] << '\n';
}
return 0;
}
The update function allocates a new node on each segment you descend, copying pointers from the previous version for untouched children, so each new version shares most of its structure. Each kth query runs in O(log m) time by comparing subtree counts of two versions.