"""Prim's minimum spanning tree.

Idea
----
Grow one tree from a start node. Keep a min-heap of edges leaving the tree
and always add the cheapest edge that reaches a new node. Compared with
Kruskal, Prim works node-by-node and suits dense graphs stored as adjacency
lists.

Complexity
----------
Time:  O(E log V) with a binary heap
Space: O(V + E)
"""

import heapq
from collections.abc import Hashable, Mapping, Sequence
from typing import TypeVar

N = TypeVar("N", bound=Hashable)


def prim(graph: Mapping[N, Sequence[tuple[N, float]]], start: N) -> float:
    """Return the MST weight of the component containing ``start``.

    ``graph`` must be undirected: list each edge in both directions.
    """
    visited = {start}
    heap: list[tuple[float, int, N]] = []
    counter = 0
    for nxt, w in graph.get(start, ()):
        heapq.heappush(heap, (w, counter, nxt))
        counter += 1
    total = 0.0
    while heap:
        w, _, node = heapq.heappop(heap)
        if node in visited:
            continue
        visited.add(node)
        total += w
        for nxt, w2 in graph.get(node, ()):
            if nxt not in visited:
                heapq.heappush(heap, (w2, counter, nxt))
                counter += 1
    return total
