Problem solution · C++

Persistent Unionfind

Persistent Unionfind: a C++ solution using disjoint set union. Learn the idea, check the complexity, and read the full code, with credit to NyaanNyaan Competitive Programming Library.

Technique
Disjoint set union
Source
NyaanNyaan Competitive Programming Library
Length
23 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Disjoint set union

For Persistent Unionfind, the implementation maintains connected components and merges them as relationships are processed.

  1. Give each element a component representative.
  2. Merge representatives when a connection is accepted.
  3. Answer connectivity or component queries from the compressed representatives.

Code notes

  • 23 lines of C++ from the credited upstream file yosupo-persistent-unionfind.test.cpp.
  • The implementation keeps its working state in language-native values and containers.
  • No explicit loop blocks detected.

Complexity

Account for every find and union operation; with path compression and ranked merging, the amortized cost is nearly constant per operation.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from NyaanNyaan Competitive Programming Library by NyaanNyaan and is used under the CC0-1.0 licence.

Full codePersistent Unionfind · C++C++
Use this to learn the idea, then write your own version.
#define PROBLEM "https://judge.yosupo.jp/problem/persistent_unionfind" #include "../../template/template.hpp"#include "../../data-structure/persistent-union-find.hpp" using namespace Nyaan; void Nyaan::solve() {  ini(N, Q);  PersistentUnionFind uf(N);  V<decltype(uf)::Node *> roots(Q + 1, nullptr);  roots[0] = uf.get_root();   rep(i, Q) {    ini(t, k, u, v);    if (t) {      auto r = roots[k + 1];      out(uf.same(u, v, r));    } else {      auto r = roots[k + 1];      uf.unite(u, v, r);      roots[i + 1] = uf.get_root();    }  }}

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗