# Union-find

Implement an in-memory **union-find** (disjoint-set) structure over the
elements `0, 1, ..., n-1`: it keeps the elements partitioned into disjoint
sets, starting with every element in a set of its own, and supports merging
two sets and asking which set an element is in.

This is the classic **disjoint-set forest** with a union heuristic and path
shortening (Galler & Fischer 1964; Tarjan 1975; CLRS, "Data Structures for
Disjoint Sets"), **not** "quick-find" (relabelling every element of a set
on a merge), explicit set objects or lists of members, a hash map from
elements to sets, or any other structure whose operations are not
near-constant time.

## Structure

- **Elements.** The elements are the integers `0 .. n-1`, where `n` is fixed
  when the structure is created and is less than 2^31. Every element passed
  to an operation is one of them; the structure need not check this.
- **A forest.** Every set is a rooted tree whose nodes are its elements.
  Every element has exactly one *parent link*: the element above it in its
  tree, or itself if it is the root. The **root** is the set's
  **representative**: `find(x)` returns the root of `x`'s tree. The
  *depth* of an element is the number of parent links from it to its root
  (a root has depth 0).
- **Flat arrays indexed by element.** The parent links are stored in an array
  indexed by element, and whatever the union heuristic needs (the size or
  rank of each root, below) in arrays indexed the same way: a small constant
  number of arrays of `n` entries each, allocated when the structure is
  created. The width of the entries is up to you. You may also pack these
  arrays into one (for example by letting a root store its size or rank in
  place of its parent link), as long as `parent(x)` reports `x` for a root.
- **Nothing else stores the sets.** No per-set objects, no lists of members,
  no map from elements to sets, no labels that are rewritten for every member
  of a set, and no cache of `find` results.
- **Union by size or by rank.** `union` finds the two roots and, if they
  differ, makes one of them a child of the other: it changes exactly one
  parent link, that of the root that stops being a root. Which root goes
  below the other is decided by one of these two heuristics, your choice:
  - *by size*: the root of the set with fewer elements becomes a child of the
    other root (on a tie, either);
  - *by rank*: every root has a rank, 0 for a new element; the root of lower
    rank becomes a child of the other, and on a tie either one does and the
    rank of the root that remains increases by 1.

  Either way, an element of a set of `s` elements is never more than
  `floor(log2(s))` levels deep.
- **Path shortening.** Every search for a root (in `find`, and in `union`,
  `connected` and `set_size`, which search the same way) shortens the path
  it follows, by one of these, your choice: *path compression* (every element
  on the path is linked directly to the root), *path halving* (every other
  element on the path is linked to its grandparent) or *path splitting*
  (every element on the path is linked to its grandparent). Either way, after
  `find(x)` an element `x` that was `d >= 2` levels deep is at most
  `ceil(d / 2)` levels deep. These are the only parent links that change
  apart from the one a `union` changes; a parent link always points to an
  element of the same tree that is nearer the root.
- **Representatives change only through `union`.** `find(x)` returns the
  same element until a `union` merges `x`'s set with another one; the merged
  set's representative is then one of the two former roots. Which elements
  are representatives is otherwise up to the implementation.

These invariants must hold after every operation returns.

## Operations

| Operation | Behaviour |
| --- | --- |
| `new(n)` | Create the structure for the elements `0 .. n-1`, each in a set of its own (`n` sets of one element). `n` may be 0. |
| `find(x) -> element` | The representative (root) of `x`'s set. Shortens the path from `x` to the root. |
| `union(a, b) -> bool` | If `a` and `b` are in different sets, merge the two sets into one, as described above, and return true. Otherwise (including when `a == b`) return false; nothing changes apart from path shortening. |
| `connected(a, b) -> bool` | Whether `a` and `b` are in the same set (`find(a) == find(b)`). |
| `set_size(x) -> count` | Number of elements in `x`'s set. |
| `sets() -> count` | Number of disjoint sets. |
| `len() -> count` | `n`, the number of elements. |
| `parent(x) -> element` | The parent link of `x`: `x` itself if `x` is a root. It changes nothing (no path shortening). |

Complexity requirements, for a structure of `n` elements:

- `new`: `O(n)`.
- `find`, `union`, `connected`, `set_size`: amortised `O(α(n))` (the inverse
  Ackermann function: near-constant), which the union heuristic and path
  shortening above give. Apart from searching for the roots, `union` is
  `O(1)`, and so is `set_size` (keep the size of every set at its root).
- `sets`, `len`, `parent`: `O(1)`. `parent` is used only to check the forest
  and is never timed.

## Rules

- Write the union-find yourself. Do not use or wrap a disjoint-set or
  union-find structure from a library (`boost::disjoint_sets`, and the like),
  and do not use a library's maps, sets or lists to hold the sets or their
  members. Plain arrays of numbers are fine.
- Use only the language's standard library. No third-party packages and no
  code in another language (no C extensions, FFI, JNI, cgo, or inline assembly).
- No architecture-specific SIMD intrinsics (`<arm_neon.h>`, `std::arch`,
  `System.Runtime.Intrinsics`, and the like). Portable features of the
  language and its compiler are fine: branch hints, prefetch hints, and
  portable vector types.
- Single-threaded: do not start threads or processes.
- Do not change process-wide runtime settings (garbage collector tuning,
  JIT flags, recursion limits, allocator replacement, and so on).
- Low-level utilities from the standard library are fine: arrays, block
  copies, bit operations, and similar.
- Memory use must be a small constant number of arrays of `n` entries each,
  allocated when the structure is created, plus a constant amount: nothing is
  allocated per set or per operation. Everything is released when the
  structure is destroyed in languages with manual memory management.
- Language features that trade safety for speed (for example `unsafe` in
  Rust) are permitted.

The exact names, signatures, and file names for your language are given in
the language binding that accompanies this specification. The benchmark
driver calls exactly that interface.

## How it is judged

1. **Correctness.** A fixed test suite drives the structure through ten
   workloads at several sizes up to 100,000 elements, and compares every
   result against a reference. The forest is checked through `parent`: every
   element must reach the root that `find` returns within `floor(log2(s))`
   parent links, `s` being the size of its set, the number of roots must be
   `sets()`, and `find` must shorten a long path as described above. Fresh
   structures are also built with long chains of unions, which a forest
   without a union heuristic turns into deep trees.
2. **Speed.** The same ten workloads are then timed on 4,000,000 elements,
   which is far larger than the CPU caches (two of them use small structures
   that fit in the caches, many times over). Only the time spent inside your
   operations is measured, so write for performance: the goal is the fastest
   correct union-find you can write in this language.
