Minimum spanning trees
Prove the cut and cycle properties, build minimum spanning trees with Kruskal, Prim and Borůvka, and apply them to clustering and approximation.
After this lesson you can
- Prove the cut and cycle properties and uniqueness with distinct weights.
- Implement Kruskal, Prim and Borůvka and choose by density and parallelism.
- Explain the ideas of the Karger–Klein–Tarjan randomized linear algorithm.
- Apply minimum spanning trees to single-linkage clustering and metric traveling salesperson approximation.
Before you start
Motivation: the cheapest network
In 1926, a Moravian electricity company asked mathematician Otakar Borůvka to design the cheapest network of lines to electrify the region’s south. His answer, published in Czech that year, is the first known algorithm for what we call a minimum spanning tree: given points and cable costs between each pair, connect all for minimum cost. The problem was rediscovered repeatedly (Jarník in 1930, Kruskal in 1956, Prim in 1957, Dijkstra in 1959) because it arises whenever connections carry costs.
- Physical networks. Wiring, pipes, roads or fiber links: cost is length and redundant connections are unnecessary.
- Hierarchical clustering. m12’s single linkage is the minimum spanning tree cut at its longest edges. HDBSCAN uses it on a density-adjusted distance.
- Probabilistic models. The Chow–Liu tree is the best tree-structured model for discrete variables, obtained as a maximum spanning tree weighted by mutual information.
- Approximation. The MST lower-bounds the optimal traveling salesperson tour, giving the factor-2 metric traveling salesperson approximation. It also underpins Steiner-tree approximations.
- Image segmentation and percolation. Merging regions by pixel-edge weight is Kruskal with a stopping rule.
The lesson has three layers. First, the problem and three classical algorithms side by side. Next, why: one cut property justifies all three, and its cycle-property twin explains what can be discarded. Finally, speed, up to Karger, Klein and Tarjan’s randomized expected-linear algorithm, and two applications. We use union-find, the indexed priority queue and exchange arguments from the greedy lesson.
The problem and three solutions
Let be a connected undirected graph with vertices, edges and weight function .
By tree characterizations, every spanning tree has exactly edges. A consequence used repeatedly: weights may be negative without changing the problem, since every candidate sums the same number of terms. If is disconnected there is no spanning tree; compute a minimum spanning forest, one MST per connected component.
Trying every candidate is infeasible. Complete graph has spanning trees (Cayley’s formula), which for is . Yet almost trivial greedy strategies solve it; three work:
- Kruskal: traverse edges from lightest to heaviest, keeping each that does not close a cycle.
- Prim: grow one tree from a vertex, always adding its lightest outgoing edge.
- Borůvka: start with fragments and in each phase join every fragment via its lightest outgoing edge, all at once.
Run the initial graph (14 vertices, 28 edges) to completion. Kruskal examines 17 edges, rejects 4 and keeps 13; Prim takes 13 steps; Borůvka finishes in 2 phases. All agree edge by edge and the tree weighs 308.0. The same holds for any other figure graph, independently of Prim’s root. Notice three things:
- Kruskal is global. It examines all graph edges by weight; fragments grow everywhere and merge.
- Prim is local. There is one tree and only outgoing edges matter. It follows Dijkstra’s pattern; a later figure compares their similarities and differences.
- Borůvka is naturally parallel. Each fragment chooses without consulting others. With vertices about phases suffice, because fragment count at least halves.
The figure graph is the points’ Gabriel graph (two points are connected if no other lies in the circle with their segment as diameter), plus some edges to nearby neighbors. This is deliberate: the Euclidean MST of planar points always lies inside the Gabriel graph, itself inside the Delaunay triangulation with edges, so the complete graph’s edges need not be examined. Thus the figure’s tree is the points’ Euclidean MST: extra edges would not change it.
The organizing question is why such different algorithms produce the same tree.
Why they work: cuts and cycles
A cut of is a vertex partition with and . An edge crosses the cut if it has one endpoint on each side. Edge set respects the cut if no edge of crosses it. A light cut edge has minimum weight among crossing edges.
Proof
Let be an MST with . If there is nothing to prove, so suppose . Adding to creates exactly one cycle , passing through . A cycle crosses a cut an even number of times (each departure must return), and already crosses it, so contains another crossing edge . Since respects the cut, . Let . Removing an edge from a cycle does not disconnect, and edge count remains , so is a spanning tree. Its weight is
because is light and crosses the cut. Thus is also minimum and contains (since ) and .
∎The next figure lets you test the property: draw a cut and verify the green edge always lies in the MST.
Two observations. The cut need not be “reasonable”: any partition works, however odd. A stronger version follows from the same proof with strict inequality: if the cut has a unique light edge , then belongs to every MST (otherwise exchange produces a strictly lighter tree, absurd). Figure weights are distinct, so green is always its cut’s unique light edge and belongs to the unique MST.
Proof
Suppose an MST contains . Removing splits into two components, defining a cut crossed by . Path joins ‘s endpoints and thus crosses that cut via some edge . Then is a spanning tree with , contradicting minimality of .
∎If is merely one of the heaviest cycle edges (ties), the same exchange gives : some MST excludes . In matroid language from the greedy lesson, graph cycles are graphic matroid circuits and minimal cuts (by inclusion, separating a connected component into exactly two) are cocircuits: the properties are dual.
The two properties ensure distinct weights give a unique MST. Its exchange proof is a good exercise at the end, and uniqueness permits unambiguous reasoning about all three algorithms.
The generic algorithm
The properties yield an algorithm maintaining set with invariant “ lies in some MST”:
- Start with , satisfying the invariant.
- While is not a tree, choose a cut respected by and add one of its light edges to . Such an edge is safe for .
The cut property preserves the invariant; when has edges it is a tree contained in an MST, hence minimum. What remains is which cut to choose, where the algorithms differ:
| Algorithm | Cut used | Edge added |
|---|---|---|
| Kruskal | one fragment of versus the rest | lightest in the graph joining distinct fragments |
| Prim | tree versus the rest | lightest leaving the tree |
| Borůvka | each fragment versus the rest, all at once | lightest leaving each fragment |
In all three cases respects the cut because its edges lie within fragments.
Kruskal
The only hard question is whether each edge closes a cycle; union-find answers exactly that: vertices are connected iff they share a representative, and accepting an edge is a union.
Correctness. When Kruskal accepts , let be the component of containing ; cut is respected by and crossed by . Every edge lighter than was already examined and either accepted (thus inside a component) or discarded because endpoints were connected and remain so. No lighter edge crosses the cut: is light and safe. When Kruskal rejects , an accepted-edge path, all lighter, joins its endpoints; is heaviest in their cycle and the cycle property says it is unnecessary. Acceptance follows from the cut, rejection from the cycle.
Cost. Sorting costs , because gives . Traversal performs at most finds and unions, costing (inverse Ackermann function). Sorting dominates. Bounded integer weights allow linear bucket sorting, making total cost . If edges arrive sorted or only the lightest need examination, early stopping saves almost everything. A modern variant, Filter-Kruskal, partitions edges like quicksort and discards cycle-closing edges early, improving practice.
Kruskal is also the graphic matroid greedy algorithm: independent sets are forests and bases are spanning trees. With weights , the greedy lesson’s Rado–Edmonds theorem proves correctness another way without new work.
Prim
Correctness follows immediately from the cut property: at each step respects cut because all its edges lie within , and the added edge is light for that cut.
Cost depends on key storage. The important operation is decreasing the key of an already queued neighbor, requiring an indexed queue:
| Key structure | Total cost | When useful |
|---|---|---|
| unsorted array | dense graph (), also vectorizable | |
| indexed binary heap | sparse graph | |
| -ary heap with | almost always, simple | |
| Fibonacci heap | Prim’s best comparison-priority-queue bound |
The array wins on dense graphs: with it costs , linear, with no structure overhead. Fibonacci heaps rarely pay off in practice due to constants but set Prim’s theoretical bound.
Prim and Dijkstra: one line apart
Prim resembles Dijkstra enough to confuse them. Both grow a tree by repeatedly extracting the smallest-key vertex. Only the key differs:
- Prim: , weight of one edge.
- Dijkstra: , length of a path from the root.
Dijkstra’s tree minimizes each root distance; Prim’s minimizes total weight, and they need not coincide: an MST does not contain all-pairs shortest paths. The smallest example is a triangle with weights , and : its MST is of weight , but the shortest path from to is the direct edge of length , omitted by the MST.
Borůvka
Correctness. Each chosen edge is light for the cut “one fragment versus the rest”, respected by , so each is individually safe. But all are added simultaneously: the cut property guarantees one edge is safe, not that all together are. Distinct weights resolve this: each fragment’s choice is its cut’s unique light edge, hence belongs to every MST, namely the unique MST; all choices are a subset of that tree and cannot form cycles.
Phase count. In a connected graph each fragment has an outgoing edge, and every new fragment merges at least two old ones. Fragment count therefore at least halves each phase and phases suffice. Each costs (one edge pass finding each fragment’s minimum), totaling . If the graph is contracted after each phase (fragments become vertices; loops and parallel edges are removed, retaining the lightest), planar-graph edge count remains proportional to vertices and costs sum geometrically: total.
Parallelism. Each fragment chooses independently. On a GPU or distributed system this takes rounds, each with work and small depth. Borůvka therefore underpins parallel MST algorithms and the Karger–Klein–Tarjan implementation below.
Implementation from scratch
All three algorithms on the same graph and checks. First union-find and Kruskal; then Prim with an indexed queue (lesson 6’s compact version) and, for dense graphs, vectorized-array Prim; finally NumPy-vectorized Borůvka, using each edge’s rank for tie-breaking and merging fragments by pointer jumping (each fragment points to the opposite endpoint’s fragment, repeating destino[destino] until all point to a root).
import time
import numpy as np
import networkx as nx
from scipy.sparse import coo_matrix
from scipy.sparse.csgraph import minimum_spanning_tree
INF = float("inf")
def grafo_aleatorio(n, m, seed):
"""Grafo conexo (un árbol aleatorio más aristas extra) con pesos distintos 1..m."""
rng = np.random.default_rng(seed)
perm = rng.permutation(n)
pares = {tuple(sorted((int(perm[i]), int(perm[rng.integers(0, i)])))) for i in range(1, n)}
while len(pares) < m:
a, b = rng.integers(0, n, 2)
if a != b:
pares.add((int(min(a, b)), int(max(a, b))))
pares = sorted(pares)
u = np.array([p[0] for p in pares]); v = np.array([p[1] for p in pares])
w = rng.permutation(len(pares)).astype(float) + 1.0
return u, v, w
class DSU:
"""Union-find con unión por tamaño y reducción de caminos a la mitad."""
def __init__(self, n):
self.p = list(range(n)); self.t = [1] * n
def buscar(self, x):
p = self.p
while p[x] != x:
p[x] = p[p[x]]; x = p[x]
return x
def unir(self, a, b):
a, b = self.buscar(a), self.buscar(b)
if a == b:
return False
if self.t[a] < self.t[b]:
a, b = b, a
self.p[b] = a; self.t[a] += self.t[b]
return True
def kruskal(n, u, v, w):
dsu, arbol = DSU(n), []
for e in np.argsort(w, kind="stable"): # el coste lo domina esta ordenación
if dsu.unir(u[e], v[e]):
arbol.append(int(e))
if len(arbol) == n - 1: # parada temprana: ya hay árbol
break
return sorted(arbol)
class ColaIndexada:
"""Montículo binario de mínimos sobre los elementos 0..n-1 con baja-clave (la de la lección 6, compacta)."""
def __init__(self, n):
self.clave = [INF] * n; self.pos = [-1] * n; self.h = []
def _sube(self, i):
h, pos, clave = self.h, self.pos, self.clave
while i > 0:
p = (i - 1) // 2
if clave[h[p]] <= clave[h[i]]:
break
h[p], h[i] = h[i], h[p]; pos[h[p]], pos[h[i]] = p, i; i = p
def _baja(self, i):
h, pos, clave = self.h, self.pos, self.clave
n = len(h)
while True:
m = i
for c in (2 * i + 1, 2 * i + 2):
if c < n and clave[h[c]] < clave[h[m]]:
m = c
if m == i:
return
h[m], h[i] = h[i], h[m]; pos[h[m]], pos[h[i]] = m, i; i = m
def bajar(self, x, k):
"""Inserta x con clave k, o le baja la clave si ya estaba."""
self.clave[x] = k
if self.pos[x] < 0:
self.h.append(x); self.pos[x] = len(self.h) - 1
self._sube(self.pos[x])
def extraer(self):
h, pos = self.h, self.pos
x = h[0]; ultimo = h.pop(); pos[x] = -2
if h:
h[0] = ultimo; pos[ultimo] = 0; self._baja(0)
return x
def lista_adyacencia(n, u, v, w):
adj = [[] for _ in range(n)]
for e in range(len(u)):
adj[u[e]].append((int(v[e]), float(w[e]), e)); adj[v[e]].append((int(u[e]), float(w[e]), e))
return adj
def prim(n, adj, raiz=0):
cola, via, arbol = ColaIndexada(n), [-1] * n, []
cola.bajar(raiz, 0.0)
while cola.h:
x = cola.extraer()
if via[x] >= 0:
arbol.append(via[x])
for y, peso, e in adj[x]:
if cola.pos[y] != -2 and peso < cola.clave[y]: # la clave es el peso de la arista, NO una distancia
via[y] = e
cola.bajar(y, peso)
return sorted(arbol)
def prim_denso(W):
"""Prim con array en O(n^2) sobre la matriz de pesos (inf = sin arista), vectorizado con NumPy."""
n = len(W)
dentro = np.zeros(n, bool); clave = np.full(n, INF); padre = np.full(n, -1)
clave[0] = 0.0
for _ in range(n):
x = int(np.argmin(np.where(dentro, INF, clave)))
dentro[x] = True
mejor = (W[x] < clave) & ~dentro
clave[mejor] = W[x][mejor]; padre[mejor] = x
return padre, clave
def boruvka(n, u, v, w):
"""Borůvka vectorizado. Ordenando antes las aristas, el índice es un desempate total."""
orden = np.argsort(w, kind="stable"); u, v = u[orden], v[orden]
m = len(u); comp = np.arange(n); arbol = np.zeros(m, bool); fases = 0
ids_v = np.arange(n)
while True:
cu, cv = comp[u], comp[v]
fuera = np.nonzero(cu != cv)[0]
if len(fuera) == 0:
break
fases += 1
mejor = np.full(n, m) # arista saliente más ligera de cada componente
np.minimum.at(mejor, cu[fuera], fuera); np.minimum.at(mejor, cv[fuera], fuera)
c = np.nonzero(mejor < m)[0]
arbol[mejor[c]] = True
e = mejor[c]
destino = ids_v.copy() # cada componente apunta a la del otro extremo
destino[c] = np.where(cu[e] == c, cv[e], cu[e])
mutuo = (destino[destino] == ids_v) & (ids_v < destino) # parejas que eligieron la misma arista
destino[mutuo] = ids_v[mutuo] # la menor de cada pareja será la raíz
while True: # salto de punteros: todo apunta a una raíz
nuevo = destino[destino]
if np.array_equal(nuevo, destino):
break
destino = nuevo
comp = destino[comp]
return sorted(int(x) for x in orden[arbol]), fases
# ---------- verificación contra SciPy y NetworkX en grafos aleatorios ----------
for n, m, semilla in [(60, 150, 0), (200, 900, 1), (500, 2500, 2)]:
u, v, w = grafo_aleatorio(n, m, semilla)
ref = minimum_spanning_tree(coo_matrix((w, (u, v)), shape=(n, n)).tocsr())
peso_ref = ref.sum()
G = nx.Graph(); G.add_weighted_edges_from(zip(u.tolist(), v.tolist(), w.tolist()))
peso_nx = sum(d["weight"] for *_, d in nx.minimum_spanning_edges(G, algorithm="kruskal"))
ka = kruskal(n, u, v, w)
pr = prim(n, lista_adyacencia(n, u, v, w))
bo, fases = boruvka(n, u, v, w)
print(f"n={n:4d} m={m:5d} pesos: scipy {peso_ref:.0f} networkx {peso_nx:.0f} | "
f"Kruskal {w[ka].sum():.0f} Prim {w[pr].sum():.0f} Borůvka {w[bo].sum():.0f} "
f"mismas aristas: {ka == pr == bo} fases de Borůvka: {fases} (cota {int(np.ceil(np.log2(n)))})")
# ---------- coste: grafo disperso y grafo denso ----------
def reloj(f, *a):
t = time.perf_counter(); r = f(*a); return r, 1000 * (time.perf_counter() - t)
n, m = 2000, 10000
u, v, w = grafo_aleatorio(n, m, 7); adj = lista_adyacencia(n, u, v, w)
_, t1 = reloj(kruskal, n, u, v, w); _, t2 = reloj(prim, n, adj); _, t3 = reloj(boruvka, n, u, v, w)
print(f"\ndisperso n={n}, m={m}: Kruskal {t1:6.1f} ms Prim con montículo {t2:6.1f} ms Borůvka {t3:6.1f} ms")
n = 400
rng = np.random.default_rng(3)
P = rng.random((n, 2)); D = np.hypot(*(P[:, None] - P[None]).transpose(2, 0, 1)); np.fill_diagonal(D, INF)
iu, ju = np.triu_indices(n, 1)
(padre, clave), t4 = reloj(prim_denso, D)
ka, t5 = reloj(kruskal, n, iu, ju, D[iu, ju])
bo, t6 = reloj(lambda: boruvka(n, iu, ju, D[iu, ju]))
print(f"denso n={n}, m={len(iu)}: Kruskal {t5:6.1f} ms Prim con array {t4:6.1f} ms Borůvka {t6:6.1f} ms "
f"(mismo peso: {abs(clave.sum() - D[iu, ju][ka].sum()) < 1e-9 and abs(clave.sum() - D[iu, ju][bo[0]].sum()) < 1e-9})")
# ---------- empates: Borůvka sin desempate crea ciclos ----------
rng = np.random.default_rng(0)
def fase_ingenua(n):
"""Grafo completo con todas las aristas de peso 1: cada vértice elige una arista incidente al azar."""
elegidas = {tuple(sorted((x, int(rng.choice([y for y in range(n) if y != x]))))) for x in range(n)}
dsu = DSU(n)
return any(not dsu.unir(a, b) for a, b in elegidas)
for n in (3, 4, 6):
ciclos = sum(fase_ingenua(n) for _ in range(2000))
print(f"K{n} con pesos iguales y desempate al azar: {100 * ciclos / 2000:.0f} % de las fases elige un ciclo")The first three output lines verify that Kruskal, Prim and Borůvka return the same edges (distinct weights give a unique tree) and match SciPy and NetworkX weights. Borůvka takes 3 or 4 phases on graphs up to 500 vertices, well below the bound of 6–9: fragments typically shrink much faster than halving. Do not infer absolute timing winners from one interpreted run: visible work is sorting and finding for Kruskal, heap key movement for Prim, -length array operations for Borůvka, and for array Prim on dense graphs without any structure. The last three lines illustrate ties: with random tie-breaking, an equal-weight triangle chooses a cycle 25% of the time (two of choices are cyclic), and the proportion grows with complete-graph size.
Can it be linear?
Reading edges already costs , so linear is optimal; the problem’s history approaches that floor:
| Algorithm | Year | Time |
|---|---|---|
| Borůvka | 1926 | |
| Kruskal, Prim with binary heap | 1956 and 1957 | |
| Prim with Fibonacci heaps (Fredman and Tarjan) | 1987 | |
| Fredman and Tarjan with bounded growth | 1987 | , with nearly constant |
| Karger, Klein and Tarjan | 1995 | expected, randomized |
| Chazelle | 2000 | , deterministic |
| Pettie and Ramachandran | 2002 | deterministic optimum, exact complexity unknown |
Whether a deterministic linear algorithm exists remains open; Karger, Klein and Tarjan (KKT) reach the floor with randomness. They use this lesson’s properties and two ideas: sample edges to get a filtering forest, then discard edges that forest proves cannot be in the tree.
Heavy and light edges
Throughout this section weights are distinct (or ties use a total order, as in Borůvka), so the MST is unique. Let be a forest of (e.g. a subgraph’s minimum forest). For edge , if and lie in different trees of , call -light; otherwise it is -light if is less than the largest weight on their path in (or if ), and -heavy otherwise.
Proof
The path of between ‘s endpoints together with forms a cycle in which is strictly heaviest. By the cycle property it is in no MST.
∎Filtering with can make the problem much smaller. How much? Randomness answers.
Proof
Traverse edges of from lightest to heaviest, flipping a coin per edge (heads with probability means “in ”), maintaining forest built by Kruskal from edges seen so far. For an edge , forest restricted to edges lighter than is exactly that partial forest, and is -light iff its endpoints are not connected by edges lighter than (otherwise the unique path has all edges lighter than and is heavy; otherwise they are disconnected or the path uses a heavier edge and is light). In other words is -light iff it joins two components of partial forest .
Each examined light edge’s coin independently lands heads with probability , and then the edge enters and component count falls by one. This happens at most times. The number of light edges is therefore at most the number of tosses until heads, a negative binomial with expectation .
∎With and vertices, at most light edges remain in expectation regardless of how many had. This is the algorithm’s core idea.
The algorithm
Correctness follows: edges are safe (Borůvka); deleted edges are heavy relative to a forest and absent from the MST (heavy-edge theorem); and the tree of lies inside , containing .
Expected time. Let and be input sizes. Steps 1 and 3 cost . Subproblem has vertices and expected edges. Subproblem has vertices and, by the sampling lemma with , at most expected edges. Thus
Induction verifies : substituting, the two subproblems contribute and local work , summing to . That is, expected time. Worst-case cost is no worse than , Borůvka’s.
import numpy as np
class DSU2:
def __init__(self, n):
self.p = list(range(n))
def buscar(self, x):
while self.p[x] != x:
self.p[x] = self.p[self.p[x]]; x = self.p[x]
return x
def unir(self, a, b):
a, b = self.buscar(a), self.buscar(b)
if a != b:
self.p[a] = b
return a != b
def grafo_ordenado(n, m, seed):
"""Aristas ordenadas por peso creciente (la posición es el peso: todos distintos)."""
rng = np.random.default_rng(seed)
perm = rng.permutation(n)
pares = {tuple(sorted((int(perm[i]), int(perm[rng.integers(0, i)])))) for i in range(1, n)}
while len(pares) < m:
a, b = rng.integers(0, n, 2)
if a != b:
pares.add((int(min(a, b)), int(max(a, b))))
pares = sorted(pares)
return [pares[i] for i in np.argsort(rng.permutation(len(pares)))]
def ligeras_por_conteo(n, aristas, p, rng):
"""Una pasada de Kruskal con una moneda por arista: cuenta las F-ligeras de la F obtenida con las muestreadas."""
dsu, ligeras, F = DSU2(n), [], []
for i, (a, b) in enumerate(aristas):
if dsu.buscar(a) != dsu.buscar(b): # une dos componentes de las muestreadas más ligeras: F-ligera
ligeras.append(i)
if rng.random() < p: # y entonces, con probabilidad p, entra en la muestra (y en F)
dsu.unir(a, b); F.append(i)
return ligeras, F
def ligeras_por_definicion(n, aristas, F):
"""Definición: e es F-ligera si sus extremos están en árboles distintos de F o pesa menos que el máximo del camino en F."""
adj = {x: [] for x in range(n)}
for i in F:
a, b = aristas[i]; adj[a].append((b, i)); adj[b].append((a, i))
def max_camino(a, b):
pila, visto = [(a, -1)], {a}
while pila:
x, mx = pila.pop()
if x == b:
return mx
for y, i in adj[x]:
if y not in visto:
visto.add(y); pila.append((y, max(mx, i)))
return None # no conectados en F
return [i for i, (a, b) in enumerate(aristas) if (mx := max_camino(a, b)) is None or i <= mx]
# 1) el recuento de una pasada coincide con la definición, y el árbol mínimo cabe en las ligeras
rng = np.random.default_rng(1)
n, m = 40, 200
aristas = grafo_ordenado(n, m, 5)
ligeras, F = ligeras_por_conteo(n, aristas, 0.5, rng)
print("coinciden con la definición (camino máximo en F):", ligeras == ligeras_por_definicion(n, aristas, F))
dsu, arbol = DSU2(n), set()
for i, (a, b) in enumerate(aristas):
if dsu.unir(a, b):
arbol.add(i)
print(f"el árbol mínimo ({len(arbol)} aristas) está dentro de las ligeras ({len(ligeras)} de {m}): {arbol <= set(ligeras)}")
# 2) lema de muestreo: E[aristas ligeras] <= (n-1)/p
n, m, intentos = 200, 2000, 60
aristas = grafo_ordenado(n, m, 11)
print()
for p in (0.5, 0.25, 0.1):
cuentas = [len(ligeras_por_conteo(n, aristas, p, rng)[0]) for _ in range(intentos)]
ee = np.std(cuentas) / np.sqrt(intentos)
print(f"p = {p:4}: media {np.mean(cuentas):6.1f} ± {ee:4.1f} cota (n-1)/p = {(n - 1) / p:6.1f} "
f"máximo observado {max(cuentas)} (m = {m})")The first check validates the proof: one-pass counting (the lemma’s technique) returns exactly edges that definition calls -light, and the MST lies inside them, as it must. The second measures the lemma: with and the observed mean matches bound within sampling error (nearly equality while enough edges remain), and of graph edges roughly and survive. With the bound becomes unattainable because the graph runs out of edges to examine.
Variants: what the MST does and does not see
Weight transformations
Kruskal only compares weights: the tree depends solely on edge order. Thus any strictly increasing weight transformation preserves the MST, while order-changing transformations can change it.
| Transformation | Preserves MST? | Reason |
|---|---|---|
| (add a constant) | yes | every tree has edges, so all gain |
| , with | yes | is strictly increasing in |
| with weights of both signs | no | and become and : order reverses |
| , with | yes | increasing. Also : minimizes the weight product |
| no | gives the maximum spanning tree |
Adding a constant preserves the MST but not shortest paths, which change because paths with more edges are penalized more: another difference from Dijkstra. A maximum spanning tree (e.g. Chow–Liu) uses the same algorithm with negated weights. The maximum-reliability tree maximizing the product of link-working probabilities is the MST with weights , combining the last two rows.
The bottleneck
The bottleneck weight of tree is . A minimum bottleneck spanning tree (MBST) minimizes . This is a different objective, but the MST satisfies it.
Proof
Let be ‘s heaviest edge, with , and suppose exists with . Removing from gives cut ; as a spanning tree, must have a crossing edge , and . But then is a lighter spanning tree than , absurd.
∎The converse is false. In a square with weights , , , , tree weighs 7 with bottleneck 4, and weighs 9 with bottleneck 4: both minimize bottleneck and only one is minimum weight. The coding exercise implements this and checks Kruskal also solves bottleneck.
A finer version useful for clustering: between any two vertices, the MST path is a minimax path.
Proof
Let be ‘s heaviest edge and suppose a path from to has all edges lighter than . Removing from puts vertices and on opposite sides of the cut (their path in used ). joins to and crosses the cut via edge with , making a lighter tree. Contradiction.
∎Ties
Repeated weights make the MST nonunique (the count uses the matrix-tree theorem, topic of m25), but all MSTs have the same multiset of weights. For each threshold , the count of edges of weight in any MST is , where is the component count of subgraph of edges with weight . By the preceding theorem, vertices connected in have a minimax path in using only edges of weight , so edges of with weight form a spanning forest of with edges. Subtract consecutive thresholds to fix the count of each exact weight. The tree’s weight profile is a graph property, not an algorithm property; clustering will use it.
Applications
Single linkage and dendrograms
Single-linkage hierarchical clustering defines distance between groups as the minimum distance between one point from each, merging the closest groups each step. Each merge is a Kruskal edge on the complete distance graph, so the merge sequence is Kruskal’s execution and heights are MST weights in increasing order. Cutting the dendrogram at means stopping Kruskal at edges heavier than : clusters are components of tree edges weighted .
Proof
If connected in the tree forest, they are connected by a chain of jumps. Conversely, a chain of jumps from to is an path of maximum weight . By the minimax-path theorem, the MST path between and has maximum weight at most and lies in the forest.
∎Merge distances also define an ultrametric (the height where two points merge, i.e. maximum weight of their minimax path satisfies , since concatenating two minimax paths gives a path from to ).
A related problem is maximum-spacing clustering: group points into clusters maximizing minimum distance between points in different clusters (spacing). Cut the MST’s heaviest edges. To prove this, let be the lightest cut-edge weight: the resulting clusters have spacing exactly . The cut edge of weight joins different clusters, and any pair , in different clusters has distance : their tree path crosses a cut edge of weight and by the minimax theorem direct edge weighs at least the path maximum. All retained edges weigh . If another grouping into clusters differs, one of our clusters contains points and in different clusters of the other. Their tree path from to lies within our cluster, all edges weigh , and some edge joins different clusters of the other grouping. Its spacing is at most .
Ties among the heaviest edges introduce a detail: there may be no threshold producing exactly clusters. You will see this in an exercise.
Chaining is a real single-linkage weakness: a row of points can join two dense groups, and one outlier reduces spacing. Variants exist: HDBSCAN computes the same tree on a locally density-adjusted distance and cuts using stability rather than a threshold.
The Chow–Liu tree
Given discrete random variables with joint distribution , seek the best approximation with tree structure (each variable depends on at most one other). With ‘s marginals and conditionals as parameters,
and the last two terms do not depend on . Minimizing divergence maximizes the sum of mutual information over tree edges: a maximum spanning tree of the complete graph with weight , computed by reversed-order Kruskal in . With data use empirical mutual information. This is the Chow–Liu tree, covered in m14.
Metric traveling salesperson approximation
Metric traveling salesperson visits points with triangle-inequality distances and returns to the source by the shortest tour. It is NP-hard, but the MST gives a nearly free -approximation.
Proof
Removing an edge from an optimal Hamiltonian circuit leaves a path that is a spanning tree, so . Doubling edges of gives a connected multigraph of even degrees, admitting an Eulerian circuit of length . Traverse it skipping already visited vertices: shortcuts replace subwalks and, by triangle inequality, do not lengthen them, leaving a Hamiltonian circuit (preorder of ) of length .
∎Christofides’ algorithm (1976) replaces doubling with a minimum-weight perfect matching among odd-degree vertices, achieving factor ; see the approximation lesson.
First compare single linkage with libraries against what we proved.
import numpy as np
import networkx as nx
from scipy.spatial.distance import pdist, squareform
from scipy.cluster.hierarchy import linkage, fcluster, cophenet
rng = np.random.default_rng(4)
X = np.vstack([rng.normal(c, 0.35, size=(20, 2)) for c in ([0, 0], [3, 0.5], [1.2, 3.2])])
n = len(X)
D0 = squareform(pdist(X))
D = D0 + np.diag(np.full(n, np.inf)) # diagonal infinita: sin lazos (misma convención que la celda de Prim)
Z = linkage(X, method="single")
# árbol mínimo euclídeo con el Prim denso de la celda anterior
padre, clave = prim_denso(D)
aristas = sorted((float(clave[v]), int(padre[v]), v) for v in range(1, n)) # (peso, u, v) del árbol mínimo
print("alturas de fusión de linkage('single') = pesos del árbol mínimo ordenados:", np.allclose([a[0] for a in aristas], Z[:, 2]))
def etiquetas_cortando(aristas, k):
"""k clusters: se borran las k-1 aristas más pesadas del árbol y se etiquetan las componentes."""
conservadas = aristas[: len(aristas) - (k - 1)]
G = nx.Graph(); G.add_nodes_from(range(n)); G.add_edges_from((u, v) for _, u, v in conservadas)
lab = np.zeros(n, int)
for c, comp in enumerate(nx.connected_components(G)):
lab[list(comp)] = c
return lab
def misma_particion(a, b):
return len({(x, y) for x, y in zip(a, b)}) == len(set(a)) == len(set(b))
for k in (2, 3, 5, 8):
print(f"k = {k}: cortar el árbol = fcluster(maxclust)? {misma_particion(etiquetas_cortando(aristas, k), fcluster(Z, k, 'maxclust'))}")
# distancia cofenética (altura a la que se unen dos puntos) = camino minimax en el grafo completo
coph = squareform(cophenet(Z))
M = D0.copy()
for k in range(n): # Floyd-Warshall con (min, max) en lugar de (min, +)
M = np.minimum(M, np.maximum(M[:, k:k + 1], M[k:k + 1, :]))
print("cofenética = camino de cuello de botella del grafo completo:", np.allclose(coph, M))
# ultramétrica: d(u,w) <= max(d(u,v), d(v,w)) para todas las ternas
viola = sum(coph[i, j] > max(coph[i, k], coph[k, j]) + 1e-12 for i in range(0, n, 6) for j in range(0, n, 6) for k in range(0, n, 6))
print("ternas que violan la desigualdad ultramétrica:", viola)The cell reuses prim_denso from above and checks the three claims: linkage heights are MST weights, cutting its heaviest edges gives the same partition as fcluster(..., 'maxclust'), and cophenetic distance is the bottleneck path (computed here with Floyd–Warshall over product rather than , the shortest-path scheme), satisfying the ultrametric inequality.
Next compare the traveling salesperson approximation against the exact subset-DP optimum on 8-point instances.
import numpy as np
from itertools import combinations
def mst_prim(D):
n = len(D)
dentro = np.zeros(n, bool); clave = np.full(n, np.inf); padre = np.full(n, -1); clave[0] = 0
for _ in range(n):
x = int(np.argmin(np.where(dentro, np.inf, clave))); dentro[x] = True
mejor = (D[x] < clave) & ~dentro
clave[mejor] = D[x][mejor]; padre[mejor] = x
return [(int(padre[v]), v) for v in range(1, n)], clave.sum()
def recorrido_doble_arbol(D):
"""2-aproximación: recorrido en preorden del árbol mínimo (equivale a un circuito euleriano con atajos)."""
aristas, peso_arbol = mst_prim(D)
hijos = {x: [] for x in range(len(D))}
for p, v in aristas:
hijos[p].append(v)
orden, pila = [], [0]
while pila:
x = pila.pop(); orden.append(x); pila.extend(reversed(hijos[x]))
longitud = sum(D[orden[i], orden[(i + 1) % len(D)]] for i in range(len(D)))
return longitud, peso_arbol
def optimo_held_karp(D):
"""Longitud del mejor circuito por programación dinámica sobre subconjuntos: O(2^n n^2)."""
n = len(D)
f = {(1 << j, j): D[0, j] for j in range(1, n)}
for tam in range(2, n):
for sub in combinations(range(1, n), tam):
S = sum(1 << j for j in sub)
for j in sub:
f[(S, j)] = min(f[(S ^ (1 << j), i)] + D[i, j] for i in sub if i != j)
todos = (1 << n) - 2
return min(f[(todos, j)] + D[j, 0] for j in range(1, n))
rng = np.random.default_rng(2)
razones, sobre_arbol = [], []
for _ in range(25):
P = rng.random((8, 2))
D = np.hypot(*(P[:, None] - P[None]).transpose(2, 0, 1))
tour, arbol = recorrido_doble_arbol(D)
opt = optimo_held_karp(D)
assert arbol <= opt + 1e-12 and opt <= tour + 1e-12 and tour <= 2 * arbol + 1e-12
razones.append(tour / opt); sobre_arbol.append(opt / arbol)
print("25 instancias de 8 puntos: árbol <= óptimo <= recorrido <= 2 * árbol, siempre")
print(f"recorrido / óptimo: media {np.mean(razones):.3f}, peor {max(razones):.3f} (garantía: 2)")
print(f"óptimo / árbol: media {np.mean(sobre_arbol):.3f}, máximo {max(sobre_arbol):.3f}")The proof’s inequalities hold on all 25 instances (checked by assertion), and the factor-2 guarantee is pessimistic: tours average longer than optimum, with sample worst case . The optimum is between and almost times tree weight, making the MST a useful branch-and-bound lower bound.
With libraries
SciPy and NetworkX provide MSTs. Their conventions matter because of three traps.
| Function | What it does | Caution |
|---|---|---|
scipy.sparse.csgraph.minimum_spanning_tree(G) | Kruskal in C on sparse or dense matrix | zero weights mean no edge; silently returns a forest for disconnected graphs |
networkx.minimum_spanning_tree(G, algorithm=...) | "kruskal" (default), "prim" or "boruvka" | pure Python; forest on disconnected graphs; maximum_spanning_tree exists |
scipy.cluster.hierarchy.linkage(X, "single") | single linkage in | MST-based algorithm; heights are its weights |
scipy.spatial.Delaunay | Euclidean MST candidate edges in | obtain the tree by running Kruskal only on these edges |
import numpy as np
import networkx as nx
from scipy.sparse import csr_matrix, coo_matrix
from scipy.sparse.csgraph import minimum_spanning_tree, connected_components
# triángulo 0-1 (peso 0), 1-2 (peso 2), 0-2 (peso 5): el árbol mínimo es {01, 12}, de peso 2
fila, col, peso = [0, 1, 0], [1, 2, 2], [0.0, 2.0, 5.0]
A = coo_matrix((peso, (fila, col)), shape=(3, 3)).tocsr()
print("aristas almacenadas en la matriz dispersa:", A.nnz) # el cero explícito sí se almacena
T = minimum_spanning_tree(A)
print("scipy: aristas del árbol devueltas:", T.nnz, "(el árbol debería tener 2); peso:", T.sum())
print("networkx:", sorted(nx.minimum_spanning_tree(nx.Graph([(0, 1, {"weight": 0.0}), (1, 2, {"weight": 2.0}), (0, 2, {"weight": 5.0})])).edges))
# remedio: sumar una constante a todos los pesos NO cambia el árbol mínimo (todo árbol tiene n-1 aristas)
A2 = A.copy(); A2.data = A2.data + 1.0
T2 = minimum_spanning_tree(A2)
print("con pesos + 1: aristas", T2.nnz, " peso real:", T2.sum() - T2.nnz)
# grafo no conexo: scipy y networkx devuelven un bosque, sin avisar
B = csr_matrix(([1.0, 2.0], ([0, 2], [1, 3])), shape=(4, 4))
ncomp, _ = connected_components(B, directed=False)
print("componentes:", ncomp, "-> aristas del bosque:", minimum_spanning_tree(B).nnz, "(n - componentes =", 4 - ncomp, ")")
# los tres algoritmos de networkx coinciden con nuestra versión (grafo y funciones de la primera celda)
u, v, w = grafo_aleatorio(300, 1500, 21)
G = nx.Graph(); G.add_weighted_edges_from(zip(u.tolist(), v.tolist(), w.tolist()))
pesos = {alg: sum(d["weight"] for *_, d in nx.minimum_spanning_edges(G, algorithm=alg)) for alg in ("kruskal", "prim", "boruvka")}
print("pesos de networkx por algoritmo:", pesos, " el nuestro:", w[kruskal(300, u, v, w)].sum())The first line confirms the surprising trap: the sparse matrix does store zero, but SciPy returns a tree missing an edge and a seemingly correct weight (2.0) by chance. Our proof gives the solution: adding a positive constant leaves the MST unchanged, and subtracting it times recovers actual weight. After adding one, the two expected edges and true weight 2.0 appear. All three NetworkX algorithms match ours, as expected.
Common mistakes
Exercises
More than one answer may be correct.
More than one answer may be correct.
Step 1 of 4. What happens when is added to ?
Step 1 of 4. Which edge do you choose?
cuello_de_botella(n, aristas), where aristas lists tuples (u, v, w) of a connected graph with vertices 0..n-1. Return (b, arbol): arbol lists the indices of edges forming a spanning tree and b is its maximum edge weight, the smallest possible for any spanning tree. With return any value for b and arbol = []. Weights may tie; tests compare against enumeration of all trees on small graphs, minimum connectivity threshold on large graphs, and the maximum weight of a Kruskal MST.def cuello_de_botella(n, aristas):
"""Devuelve (b, arbol): b = menor peso máximo posible, arbol = índices de n-1 aristas que lo alcanzan."""
# tu código: ¿qué árbol sabes que ya minimiza el peso máximo?
return None, []Summary
- Cut and cycle. A lightest edge of a cut respecting the partial tree is safe; a strictly heaviest cycle edge belongs to no MST. Distinct weights give a unique tree.
- Kruskal sorts edges and accepts those joining distinct components (union-find), in dominated by sorting. Prim grows a tree with an indexed priority queue in , with Fibonacci or with an array on dense graphs. Borůvka runs phases with many independent choices and is naturally parallel.
- Prim is not Dijkstra. Prim’s key is one edge weight, Dijkstra’s an accumulated distance. Their trees differ: an MST does not contain shortest paths.
- Ties. Repeated weights require a total tie-break in Borůvka. The tree ceases to be unique, but all MSTs share their weight multiset.
- Variants. The tree depends only on weight order (adding constants, squaring positive weights or logarithms preserve it; yields the maximum). Every MST minimizes maximum weight and its paths are minimax paths.
- Linear time. Karger, Klein and Tarjan combine two Borůvka phases, edge sampling and forest-based heavy-edge filtering for expected . The sampling lemma, with expected light edges, is key.
- Applications. Single linkage is Kruskal cut at a height (with minimax-path ultrametric), Chow–Liu is a maximum tree on mutual information, and MST preorder gives a 2-approximation for metric traveling salesperson.