TExcelTAD
Home › Graph Algorithms › The Generic Method, Cuts and Light Edges

The Generic Method, Cuts and Light Edges

A company wants to connect seven offices with leased lines so that every office can reach every other, and each possible line has a monthly price. The cheapest network contains no cycle, since dropping one edge of a cycle keeps everything connected and saves money. So the answer is a spanning tree, a tree that contains every vertex, of minimum total weight: a minimum spanning tree (MST). The same problem appears in circuit wiring, clustering, and as a building block of approximation algorithms for the travelling salesman problem. The DSA course introduces MSTs by example. This lesson proves the one fact that both classic algorithms, Kruskal's and Prim's, are built on.

The problem

Given a connected undirected graph G=(V,E)G = (V, E) with weights w:E→Rw : E \to \mathbb{R}, find an acyclic subset T⊆ET \subseteq E that connects all vertices and minimizes

w(T)=∑(u,v)∈Tw(u,v)w(T) = \sum_{(u, v) \in T} w(u, v)

A spanning tree always has exactly V−1V - 1 edges. There can be exponentially many: the program enumerates every subset of V−1V - 1 edges of a seven-vertex graph, keeps those that form a spanning tree, and finds the cheapest.

python · try it yourself
from itertools import combinations

edges = [("A", "B", 7), ("A", "D", 4), ("B", "C", 8), ("B", "D", 9), ("B", "E", 3), ("C", "E", 6),
         ("C", "F", 10), ("D", "E", 11), ("D", "G", 5), ("E", "F", 2), ("E", "G", 12), ("F", "G", 1)]
V = "ABCDEFG"

def is_spanning_tree(subset):
    parent = {v: v for v in V}
    def find(x):
        while parent[x] != x:
            x = parent[x]
        return x
    for u, v, _ in subset:
        ru, rv = find(u), find(v)
        if ru == rv:
            return False                       # this edge closes a cycle
        parent[ru] = rv
    return True                                 # V - 1 edges and no cycle: a spanning tree

trees = [t for t in combinations(edges, len(V) - 1) if is_spanning_tree(t)]
weights = sorted(sum(w for _, _, w in t) for t in trees)
best = min(trees, key=lambda t: sum(w for _, _, w in t))
print(f"{len(trees)} spanning trees among {len(list(combinations(edges, 6)))} subsets of 6 edges")
print("lightest weights:", weights[:5], " heaviest:", weights[-1])
print("an MST:", ", ".join(f"{u}{v}:{w}" for u, v, w in best))
308 spanning trees among 924 subsets of 6 edges
lightest weights: [21, 23, 23, 24, 25]  heaviest: 57
an MST: AD:4, BE:3, CE:6, DG:5, EF:2, FG:1

Enumeration is hopeless beyond toy sizes: a complete graph on nn vertices has nn−2n^{n-2} spanning trees (Cayley's formula). The greedy algorithms below find an MST in O(Elg⁡V)O(E \lg V) time instead.

The generic method

Both algorithms grow a set of edges AA and keep one invariant:

Invariant: AA is a subset of some minimum spanning tree.

An edge (u,v)(u, v) is safe for AA if A∪{(u,v)}A \cup \{(u, v)\} is still a subset of some MST.

text
GENERIC-MST(G, w)
1  A = empty set
2  while A does not form a spanning tree
3      find an edge (u, v) that is safe for A
4      A = A + {(u, v)}
5  return A

The empty set satisfies the invariant, adding a safe edge keeps it, and when the loop ends AA is a spanning tree contained in an MST, so it is an MST. Everything hinges on line 3: how do we recognise a safe edge?

Cuts and light edges

A cut (S,V∖S)(S, V \setminus S) is a partition of the vertices into two non-empty sides. An edge crosses the cut if one endpoint is in SS and the other is not. A cut respects a set AA of edges if no edge of AA crosses it. An edge is a light edge crossing the cut if its weight is the minimum among all edges crossing the cut (there can be ties).

Theorem (cut property). Let AA be a subset of some MST TT, let (S,V∖S)(S, V \setminus S) be any cut that respects AA, and let (u,v)(u, v) be a light edge crossing it. Then (u,v)(u, v) is safe for AA.

Proof

If (u,v)∈T(u, v) \in T there is nothing to prove. Otherwise adding (u,v)(u, v) to TT creates exactly one cycle: the edge plus the path pp from uu to vv in TT. Since uu and vv are on opposite sides of the cut, pp crosses the cut at least once, say at edge (x,y)(x, y). That edge is not in AA, because the cut respects AA. Remove it and add (u,v)(u, v):

T′=T∖{(x,y)}∪{(u,v)}T' = T \setminus \{(x, y)\} \cup \{(u, v)\}

T′T' is a spanning tree: removing (x,y)(x, y) splits TT into two pieces, one containing uu and one containing vv, and (u,v)(u, v) joins them again. Because (u,v)(u, v) is light and (x,y)(x, y) also crosses the cut, w(u,v)≤w(x,y)w(u, v) \le w(x, y), so w(T′)≤w(T)w(T') \le w(T). TT is minimum, so T′T' is minimum too. Finally A⊆T′A \subseteq T' (we removed only (x,y)∉A(x, y) \notin A) and (u,v)∈T′(u, v) \in T', so A∪{(u,v)}⊆T′A \cup \{(u, v)\} \subseteq T'.

Corollary. Let AA be a subset of some MST, and let CC be one of the connected components (trees) of the forest (V,A)(V, A). A light edge connecting CC to a vertex outside CC is safe for AA. (Use the cut (C,V∖C)(C, V \setminus C), which respects AA.)

The two algorithms are the two natural ways to pick the cut. Prim grows a single tree and always cuts it off from the rest. Kruskal takes the globally lightest edge joining two different trees, which is light for the cut around either tree.

Any respecting cut works

The theorem allows any cut that respects AA, not just the ones Prim and Kruskal use. The program runs the generic method 300 times, each time choosing a random cut that respects AA: it colours each tree of the forest (V,A)(V, A) randomly as "in SS" or "not in SS" (retrying if a side is empty), then adds a light crossing edge. Every run ends with weight 21, the minimum found by enumeration. It also shows what goes wrong with a crossing edge that is not light.

python · try it yourself
import random

edges = [("A", "B", 7), ("A", "D", 4), ("B", "C", 8), ("B", "D", 9), ("B", "E", 3), ("C", "E", 6),
         ("C", "F", 10), ("D", "E", 11), ("D", "G", 5), ("E", "F", 2), ("E", "G", 12), ("F", "G", 1)]
V = "ABCDEFG"

def components(A):
    comp = {v: v for v in V}
    changed = True
    while changed:                               # simple label propagation, fine for 7 vertices
        changed = False
        for u, v, _ in A:
            m = min(comp[u], comp[v])
            if comp[u] != m or comp[v] != m:
                comp[u] = comp[v] = m
                changed = True
    return comp

def generic_mst(rng, pick):
    A = []
    while len(A) < len(V) - 1:
        comp = components(A)
        trees = sorted(set(comp.values()))
        while True:
            side = {t: rng.random() < 0.5 for t in trees}
            if 0 < sum(side.values()) < len(trees):
                break
        S = {v for v in V if side[comp[v]]}
        crossing = [e for e in edges if (e[0] in S) != (e[1] in S)]
        A.append(pick(rng, crossing))
    return sum(w for _, _, w in A)

rng = random.Random(4)
light = lambda rng, crossing: min(crossing, key=lambda e: e[2])
results = {generic_mst(rng, light) for _ in range(300)}
print("light edges, 300 random respecting cuts: final weights", results)
anyedge = lambda rng, crossing: rng.choice(crossing)
results = sorted({generic_mst(rng, anyedge) for _ in range(300)})
print("arbitrary crossing edges: weights from", results[0], "to", results[-1])
light edges, 300 random respecting cuts: final weights {21}
arbitrary crossing edges: weights from 21 to 57

Choosing an arbitrary crossing edge still produces a spanning tree (a crossing edge never closes a cycle, because its ends lie in different trees of AA), but its weight can be far from minimal. Lightness is the whole point.

Note: The cut property is the greedy-choice property of the MST problem: a locally cheapest choice can always be extended to a global optimum. Spanning trees are also the bases of a graphic matroid (Matroids), and Kruskal's algorithm is exactly the matroid greedy algorithm.

Test yourself

A connected graph has 10 vertices. How many edges does every spanning tree have?

  1. 10
  2. 9
  3. 45
  4. It depends on the weights

The cut (S,V∖S)(S, V \setminus S) respects AA, and (u,v)(u, v) is a light edge crossing it. Which statement is the cut property?

  1. (u,v)(u, v) belongs to every MST
  2. A∪{(u,v)}A \cup \{(u, v)\} is contained in some MST
  3. (u,v)(u, v) is the lightest edge of the graph
  4. Every edge crossing the cut is safe

In the proof of the cut property, why is the removed edge (x,y)(x, y) not in AA?

  1. Because it is the heaviest edge of TT
  2. Because it crosses the cut, and no edge of AA crosses a cut that respects AA
  3. Because TT has no cycles
  4. Because (x,y)=(u,v)(x, y) = (u, v)

Why does adding any crossing edge (light or not) to AA never create a cycle in the generic method with a respecting cut?

  1. Because the graph is a tree
  2. Because a crossing edge joins two different trees of the forest (V,A)(V, A)
  3. Because crossing edges are always light
  4. It can create a cycle