Problem solution · C++

Range Parallel Unionfind

Range Parallel 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
38 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 Range Parallel 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

  • 38 lines of C++ from the credited upstream file yosupo-range-parallel-unionfind.test.cpp.
  • The implementation visibly relies on sequence storage.
  • 1 loop block 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 codeRange Parallel Unionfind · C++C++
Use this to learn the idea, then write your own version.
#define PROBLEM "https://judge.yosupo.jp/problem/range_parallel_unionfind"//#include "../../template/template.hpp"//#include "../../data-structure/parallel-union-find.hpp"//#include "../../modint/montgomery-modint.hpp"//using namespace Nyaan;using mint = LazyMontgomeryModInt<998244353>;// using mint = LazyMontgomeryModInt<1000000007>;using vm = vector<mint>;using vvm = vector<vm>; using namespace Nyaan; void q() {  ini(N, Q);  vm X(N);  in(X);   ParallelUnionFind uf(N);  mint ans = 0;  rep(i, Q) {    inl(k, a, b);    uf.unite(a, a + k, b, b + k, [&](int x, int y) {      ans += X[x] * X[y];      X[x] += X[y];    });    out(ans);  }} void Nyaan::solve() {  int t = 1;  // in(t);  while (t--) q();}

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 ↗