"""Union-find (disjoint set union, DSU).

Idea
----
Track which elements belong to the same group. Each group is a tree; its
root is the group's representative.

* ``find`` walks up to the root and applies *path compression*: every node
  on the way is pointed straight at the root.
* ``union`` links the root of the smaller tree under the larger one
  (*union by size*), keeping trees shallow.

With both tricks, each operation costs O(alpha(n)) amortised, where alpha is
the inverse Ackermann function: below 5 for any input that fits in memory.

Used by Kruskal's MST, connected components, and percolation/grid problems.
"""

from collections.abc import Hashable, Iterable
from typing import Any


class UnionFind:
    def __init__(self, items: Iterable[Hashable] = ()) -> None:
        self.parent: dict[Any, Any] = {}
        self.size: dict[Any, int] = {}
        self.groups = 0
        for item in items:
            self.add(item)

    def add(self, item: Hashable) -> None:
        if item not in self.parent:
            self.parent[item] = item
            self.size[item] = 1
            self.groups += 1

    def find(self, item: Hashable) -> Any:
        self.add(item)
        root = item
        while self.parent[root] != root:
            root = self.parent[root]
        while self.parent[item] != root:  # path compression
            self.parent[item], item = root, self.parent[item]
        return root

    def union(self, a: Hashable, b: Hashable) -> bool:
        """Merge the groups of ``a`` and ``b``. Return False if already joined."""
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False
        if self.size[ra] < self.size[rb]:
            ra, rb = rb, ra
        self.parent[rb] = ra
        self.size[ra] += self.size[rb]
        self.groups -= 1
        return True

    def connected(self, a: Hashable, b: Hashable) -> bool:
        return self.find(a) == self.find(b)
