class UnionFind:
    """Maintain disjoint components with size-based unions and compression.

    Attributes:
        parent: Parent index for each vertex; roots point to themselves.
        size: Component sizes, meaningful only at current roots.
        components: Current number of disjoint components.
    """

    def __init__(self, count: int) -> None:
        """Create one component per vertex numbered from zero.

        Args:
            count: Nonnegative number of vertices.

        Raises:
            ValueError: If count is negative.
        """
        if count < 0:
            raise ValueError("Vertex count must be nonnegative.")
        self.parent = list(range(count))
        self.size = [1] * count
        self.components = count

    def find(self, item: int) -> int:
        """Return the root and compress the path from item to that root.

        Args:
            item: Vertex index in the half-open range [0, count).

        Returns:
            The representative of the component containing item.

        Raises:
            IndexError: If item is outside the vertex range.
        """
        if not 0 <= item < len(self.parent):
            raise IndexError("Vertex index is out of range.")
        root = item
        while self.parent[root] != root:
            root = self.parent[root]
        while item != root:
            following = self.parent[item]
            self.parent[item] = root
            item = following
        return root

    def union(self, left: int, right: int) -> bool:
        """Merge two components if they are currently distinct.

        Args:
            left: One vertex index.
            right: Another vertex index.

        Returns:
            True if two components merged, or False if already connected.

        Raises:
            IndexError: If either index is outside the vertex range.
        """
        left_root = self.find(left)
        right_root = self.find(right)
        if left_root == right_root:
            return False
        if self.size[left_root] < self.size[right_root]:
            left_root, right_root = right_root, left_root
        self.parent[right_root] = left_root
        self.size[left_root] += self.size[right_root]
        self.components -= 1
        return True


groups = UnionFind(6)
print("Initial parents:", groups.parent)
print("Initial components:", groups.components)

edges = [(0, 1), (2, 3), (1, 2), (4, 5), (0, 2)]
for left, right in edges:
    merged = groups.union(left, right)
    root_sizes = {
        item: groups.size[item]
        for item in range(len(groups.parent))
        if groups.parent[item] == item
    }
    print("Edge:", (left, right), "Merged:", merged)
    print("Parents:", groups.parent)
    print("Root sizes:", root_sizes, "Components:", groups.components)

print("Before find(3):", groups.parent)
print("Root of 3:", groups.find(3))
print("After find(3):", groups.parent)
print("Same component for 0 and 3:", groups.find(0) == groups.find(3))
print("Same component for 0 and 5:", groups.find(0) == groups.find(5))

def count_components(count: int, edges: list[tuple[int, int]]) -> int:
    """Count connected components in an undirected graph.

    Args:
        count: Nonnegative number of vertices labeled from zero.
        edges: Endpoint pairs, including any duplicates or self-loops.

    Returns:
        The number of connected components, including isolated vertices.

    Raises:
        ValueError: If count is negative.
        IndexError: If an endpoint is outside the vertex range.
    """
    groups = UnionFind(count)
    for left, right in edges:
        groups.union(left, right)
    return groups.components


for count, edges, expected in [
    (0, [], 0),
    (1, [], 1),
    (4, [], 4),
    (4, [(0, 1), (1, 2)], 2),
    (3, [(0, 1), (1, 2), (2, 0)], 1),
    (3, [(0, 1), (0, 1), (2, 2)], 2),
]:
    answer = count_components(count, edges)
    assert answer == expected
    print("Vertices:", count, "Edges:", edges, "Components:", answer)

for count, edges in [(-1, []), (3, [(-1, 0)]), (3, [(0, 3)])]:
    try:
        count_components(count, edges)
    except (ValueError, IndexError) as error:
        print(type(error).__name__, str(error))
