"""Bellman-Ford shortest paths (negative weights allowed).

Idea
----
A shortest path in a graph with V nodes uses at most V - 1 edges. So relax
*every* edge V - 1 times; after round i, all shortest paths with at most i
edges are correct. If an edge can still be relaxed in round V, some cycle has
negative total weight and shortest paths are undefined.

Complexity
----------
Time:  O(V * E)
Space: O(V)

When to use
-----------
Graphs with negative edges, or when you need to detect negative cycles
(for example currency arbitrage).
"""

from collections.abc import Hashable, Iterable, Sequence
from typing import TypeVar

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


def bellman_ford(
    nodes: Iterable[N], edges: Sequence[tuple[N, N, float]], source: N
) -> dict[N, float]:
    """Return shortest distances from ``source``.

    ``edges`` holds ``(u, v, weight)`` triples. Unreachable nodes map to
    ``inf``. Raises ValueError if a negative cycle is reachable.
    """
    dist = {node: float("inf") for node in nodes}
    dist[source] = 0
    for _ in range(len(dist) - 1):
        changed = False
        for u, v, w in edges:
            if dist[u] + w < dist[v]:
                dist[v] = dist[u] + w
                changed = True
        if not changed:
            break
    for u, v, w in edges:
        if dist[u] + w < dist[v]:
            raise ValueError("graph contains a negative-weight cycle")
    return dist
