YS - Perisistent Union Find

Author: Chongtian Ma

Table of Contents

ExplanationImplementation

Explanation

Using a data structure that can undo any past consecutive changes, we can solve this problem by processing queries offline. Let's construct a directed graph of queries. The uu'th query and the vv'th query has a directed edge iff kv=uk_v = u, in other words, the vv'th query is using the graph from query uu. Thus using DFS, when we recurse through the graph we are simply processing queries, and when we exit our recursion we are simply undoing queries (this is possible due to using rollbacks)!

Implementation

C++

#include <bits/stdc++.h>
using namespace std;
struct DSU {
vector<int> p, sz;
// stores info from the past
vector<pair<int, int>> past_parent, past_size;
DSU(int n) {
p.resize(n);
sz.resize(n, 1);

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!