YS - Perisistent Union Find
Author: Chongtian Ma
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 'th query and the 'th query has a directed edge iff , in other words, the 'th query is using the graph from query . 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 pastvector<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!