Python 3D Academyবাংলা

Kruskal's algorithm, with union-find

🌍 In real life. The power company collects a price for every possible cable and sorts the list, cheapest first. A clerk goes down the list. For each cable they ask one question: "do these two villages already have power from each other through cables we chose earlier?" If not, they approve it. If yes, the cable would only close a loop, so they skip it.

The idea in one sentence: Kruskal's algorithm tries the edges cheapest first and keeps each one that joins two different groups; union-find (Chapter 53) answers "same group?" in nearly constant time.

Its words:

  • Kruskal's algorithm: build the MST by taking the cheapest edge that doesn't close a loop, again and again
  • union-find (DSU): the structure from Lesson 53.2; union(a, b) merges two groups and returns False when they were already one

Step by step:

  1. sort the cables by price
  2. start with every village its own group
  3. for each cable, cheapest first: if union(a, b) succeeds, the cable is in the tree; if it returns False, skip it
  4. stop when the tree has V − 1 cables (or when the list runs out)

Watch it on the six villages. A–B for 4 is skipped because A and B are already joined through C, and the dearest cable, E–F, is never even tried:

Why it works. A skipped cable closes a loop, and Lesson 55.1 showed a loop is never needed. A taken cable is the cheapest one that joins one end's group to another group: every cheaper cable was tried already and either joined groups or sat inside one. Lesson 55.4 proves that such a cable is always safe to take, so every cable Kruskal takes belongs in a minimum spanning tree.

What it costs, by counting. Sorting E cables takes about E × log₂ E comparisons, and then each cable costs two near-constant finds. For 100,000 possible cables that is about 100,000 × 17 = 1,700,000 comparisons for the sort and 200,000 finds: O(E log E), almost all of it the sort. The brute force of Lesson 55.1 couldn't even finish 40 cables.

class DSU:
    def __init__(self, n):
        self.parent = list(range(n))
        self.rank = [0] * n            # an upper bound on each tree's height
        self.groups = n

    def find(self, x):
        root = x
        while self.parent[root] != root:
            root = self.parent[root]
        while self.parent[x] != root:  # path compression: point the path at the leader
            nxt = self.parent[x]
            self.parent[x] = root
            x = nxt
        return root

    def union(self, a, b):
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False
        if self.rank[ra] < self.rank[rb]:
            ra, rb = rb, ra            # union by rank: the shorter tree goes under
        self.parent[rb] = ra
        if self.rank[ra] == self.rank[rb]:
            self.rank[ra] += 1
        self.groups -= 1
        return True

def kruskal(vertices, cables):
    index = {v: i for i, v in enumerate(vertices)}
    d = DSU(len(vertices))
    total, tree = 0, []
    for a, b, w in sorted(cables, key=lambda c: c[2]):   # cheapest first
        if len(tree) == len(vertices) - 1:
            break                                         # V - 1 cables: the tree is done
        if d.union(index[a], index[b]):                   # different groups: take it
            total += w
            tree.append((a, b, w))
    return total, tree

total, tree = kruskal(["A", "B", "C", "D", "E", "F"], [("A", "B", 4), ("A", "C", 3), ("B", "C", 2), ("B", "D", 5), ("C", "D", 6), ("C", "E", 7), ("D", "E", 1), ("D", "F", 8), ("E", "F", 9)])
print(total)
print(tree)

Mistakes and edge cases.

  • sorted(cables) on (a, b, w) tuples: that sorts by the first village's name, not by price; sort with key=lambda c: c[2], or store cables as (w, a, b)
  • a "seen" set instead of union-find: after A–B and C–D, all four villages are seen, yet B–C joins two different groups and must be taken
  • not checking the end: if the villages can't all be connected, the loop finishes with fewer than V − 1 cables; check d.groups == 1 before calling it a spanning tree
  • equal prices: Kruskal takes one of the cheapest, and any choice gives the same total

Quiz

  1. In what order does Kruskal's algorithm try the cables?

    • Cheapest first
    • Outward from a starting village
    • In the order they were given
  2. What does this print?

    class DSU:
        def __init__(self, n):
            self.parent = list(range(n))
            self.rank = [0] * n            # an upper bound on each tree's height
            self.groups = n
    
        def find(self, x):
            root = x
            while self.parent[root] != root:
                root = self.parent[root]
            while self.parent[x] != root:  # path compression: point the path at the leader
                nxt = self.parent[x]
                self.parent[x] = root
                x = nxt
            return root
    
        def union(self, a, b):
            ra, rb = self.find(a), self.find(b)
            if ra == rb:
                return False
            if self.rank[ra] < self.rank[rb]:
                ra, rb = rb, ra            # union by rank: the shorter tree goes under
            self.parent[rb] = ra
            if self.rank[ra] == self.rank[rb]:
                self.rank[ra] += 1
            self.groups -= 1
            return True
    
    def kruskal(vertices, cables):
        index = {v: i for i, v in enumerate(vertices)}
        d = DSU(len(vertices))
        total, tree = 0, []
        for a, b, w in sorted(cables, key=lambda c: c[2]):   # cheapest first
            if len(tree) == len(vertices) - 1:
                break                                         # V - 1 cables: the tree is done
            if d.union(index[a], index[b]):                   # different groups: take it
                total += w
                tree.append((a, b, w))
        return total, tree
    
    print(kruskal(["A", "B", "C"], [("A", "B", 3), ("B", "C", 1), ("A", "C", 2)]))
  3. Why can't a set of villages already seen replace union-find?

    • Two villages can both be seen yet sit in different groups, like B and C after A–B and C–D
    • Sets are too slow
    • Sets can't hold strings
  4. Kruskal on 100,000 possible cables: where does most of the work go?

    • Sorting: about 1,700,000 comparisons, against 200,000 near-constant finds
    • The finds: about 10,000,000,000 steps
    • Trying every set of cables
  5. This sometimes builds a dearer network than needed. Which line is wrong?

    def kruskal(vertices, cables):
        index = {v: i for i, v in enumerate(vertices)}
        d = DSU(len(vertices))
        total, tree = 0, []
        for a, b, w in sorted(cables):
            if d.union(index[a], index[b]):
                total += w
                tree.append((a, b, w))
        return total, tree

Coding tasks

  1. DSU (Lesson 53.2) is written for you. Write kruskal(vertices, cables): cables are (a, b, price). Return (total, tree): the MST's total price and its cables in the order Kruskal takes them. Sort with key=lambda c: c[2], so cables of equal price keep their given order.

  2. DSU is written for you. The villages are numbered 0 to n - 1. Write connect_cost(n, cables): the cheapest total price to connect all n villages, or -1 if the cables can't connect them all.