Disjoint Set Union with Rollback
Omit path compression and unite by size so every merge mutates only two entries. Recording modified pairs on a stack enables O(log n) queries with divide-and-conquer on time.
struct RollbackDSU {
vector<int> p, sz;
vector<pair<int,int>> hist;
RollbackDSU(int n) : p(n), sz(n, 1) { iota(p.begin(), p.end(), 0); }
int find(int x) const { return p[x] == x ? x : find(p[x]); }
bool unite(int a, int b) {
a = find(a); b = find(b);
if (a == b) return false;
if (sz[a] < sz[b]) swap(a, b);
hist.push_back({b, sz[a]});
p[b] = a; sz[a] += sz[b];
return true;
}
void rollback(int snap) {
while ((int)hist.size() > snap) {
auto [b, old] = hist.back(); hist.pop_back();
int a = p[b]; sz[a] = old; p[b] = b;
}
}
};