"""Dijkstra's shortest paths (non-negative weights).

Idea
----
Keep a priority queue of (distance so far, node). Always expand the closest
unfinished node: with non-negative weights nothing discovered later can give
it a shorter distance, so its distance is final. Relax each outgoing edge,
pushing a new entry whenever a shorter distance is found. Stale entries are
skipped when popped ("lazy deletion"), which is simpler than decrease-key.

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

Pitfall
-------
Negative edge weights break the "closest is final" argument. Use
Bellman-Ford for those.
"""

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

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


def dijkstra(graph: Mapping[N, Sequence[tuple[N, float]]], source: N) -> dict[N, float]:
    """Return the shortest distance from ``source`` to every reachable node."""
    dist: dict[N, float] = {source: 0}
    heap: list[tuple[float, int, N]] = [(0, 0, source)]
    counter = 1  # tie-breaker so nodes never need to be comparable
    while heap:
        d, _, node = heapq.heappop(heap)
        if d > dist[node]:
            continue  # stale entry
        for nxt, weight in graph.get(node, ()):
            if weight < 0:
                raise ValueError("Dijkstra requires non-negative weights")
            nd = d + weight
            if nd < dist.get(nxt, float("inf")):
                dist[nxt] = nd
                heapq.heappush(heap, (nd, counter, nxt))
                counter += 1
    return dist
