Skip to content

Prim's cheapest links

networks

Level 2 of 3

Also called Prim's algorithm and Minimum spanning tree.

how it works

The idea on a small map, then one run on the town of eight, from A.

Prim's method joins every place with the least road in all, as when wiring a town. A trip along those roads may be long: section 7 draws one. Prim's grows one tree. Write 0 at the start: it needs no road. A place with a length written, not joined yet, is waiting. Repeat until no place waits: join the waiting place with the cheapest road written, along that road. Two equal go in letter order. Then look along each of its roads to a place not joined yet. If that place has no road written, or this road is cheaper, write this road's length there. The watch page finds the cheapest by a scan: each round it weighs up every place waiting. This page counts those, so a place that waits three rounds counts three times. The code below, in the language Python, uses a heap instead, as section 4's question 5 explains.

92213ABCEF
Start at A, shaded. A to B alone is 9, and a cheaper road to B comes late. The cheapest links, heavy, add up to 2 + 2 + 1 + 3, which is 8.
roundwaitingjoinslooks alongwrites
1A 0AA-B, A-EB 9, E 2
2B 9, E 2E by A-EE-FF 2
3B 9, F 2F by E-FF-BB 1, beating 9
4B 1B by F-BB-CC 3
5C 3C by B-Cnonenone
B 9 means 9 written at B. The places waiting are those weighed up, 1 + 2 + 2 + 1 + 1, which is 7.
Wiring a town of eight places: 8 moments of its 21 steps, the steps between them left for the watch page
  1. step 1 of 21

    426531728324A0BCDEFGH

    Start the tree at A. It needs no road to join, so write 0 there.

    what it remembers to know where it is
    joined last
    not yet
    road in the tree
    0

    Where it says not yet, nothing is held there at that moment.

    watch from here

  2. step 4 of 21

    426531728324A0B4CDE2F6GH

    The road from A to F is 6 long, cheaper than any road to F found before. Write 6 at F.

    what it remembers to know where it is
    joined last
    A
    road in the tree
    0

    watch from here

  3. step 5 of 21

    426531728324A0B4CDE2F6GH

    E has the cheapest road to the tree, 2 long from A. Join E with that road: the tree now has 2 of road.

    what it remembers to know where it is
    joined last
    E
    road in the tree
    2

    watch from here

  4. step 8 of 21

    426531728324A0B1CDE2F3GH

    The road from F to B is 1 long, cheaper than any road to B found before. Write 1 at B.

    what it remembers to know where it is
    joined last
    F
    road in the tree
    5

    watch from here

  5. step 10 of 21

    426531728324A0B1CDE2F3G7H

    B has the cheapest road to the tree, 1 long from F. Join B with that road: the tree now has 6 of road.

    what it remembers to know where it is
    joined last
    B
    road in the tree
    6

    watch from here

  6. step 14 of 21

    426531728324A0B1C5D8E2F3G2H

    The road from C to G is 2 long, cheaper than any road to G found before. Write 2 at G.

    what it remembers to know where it is
    joined last
    C
    road in the tree
    11

    watch from here

  7. step 19 of 21

    426531728324A0B1C5D2E2F3G2H3

    The road from H to D is 2 long, cheaper than any road to D found before. Write 2 at D.

    what it remembers to know where it is
    joined last
    H
    road in the tree
    16

    watch from here

  8. step 21 of 21

    426531728324A0B1C5D2E2F3G2H3

    Done: no place is left with a road to the tree. The cheapest links join the 8 places with 18 of road.

    what it remembers to know where it is
    joined last
    not yet
    road in the tree
    18

    Where it says not yet, nothing is held there at that moment.

    watch from here

the steps, in plain words
  1. start the tree at the start: it needs no road, so write 0 therePython line 25
  2. join the place not in the tree with the cheapest road to it, and that roadPython lines 30, 31, 32 and 33
  3. look along each road from it to a place not in the treePython lines 34, 35 and 36
  4. if it is cheaper than the road written there, write its length therePython lines 37, 38, 39 and 40
  5. if not, keep the road written therePython line 41
  6. when no place left has a road to it, the roads joined are the cheapest linksPython lines 29, 42, 47 and 48
the same in Python

The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.

from heapq import heappop, heappush


def prim(roads, start):
    """Find the cheapest links that join every place start can reach.

    roads is a list of (place, place, length), each road running both
    ways. Returns the length written at each place joined: the road that
    joined it, and 0 at start. They add up to the links' total. A place
    no road leads to from start is left out.
    """
    return grow(neighbours(roads), start)[0]


def neighbours(roads):
    """Each place's roads, as pairs of the place at the far end and the length."""
    near = {}
    for a, b, length in roads:  # a road runs both ways
        near.setdefault(a, []).append((b, length))
        near.setdefault(b, []).append((a, length))
    return near


def grow(near, start):
    written = {start: 0}  # the start needs no road, so write 0 there
    came_from = {}  # the place each written road comes from
    joined = set()
    heap = [(0, start)]  # entries of length and place, cheapest on top
    while heap:  # none left: no place left has a road to the tree
        _, here = heappop(heap)  # the cheapest; on a tie, first in letter order
        if here in joined:  # an old entry: a cheaper one came first
            continue
        joined.add(here)  # join it, with the road written there
        for there, length in near.get(here, []):  # each road from it
            if there in joined:  # only to a place not in the tree
                continue
            if there not in written or length < written[there]:  # cheaper?
                written[there] = length  # write its length there
                came_from[there] = here
                heappush(heap, (length, there))
            # if not, keep the road written there
    return written, came_from


def cheapest_links(roads, start):
    """The roads joined, each as (place, place it came from), by letter."""
    _, came_from = grow(neighbours(roads), start)
    return sorted(came_from.items())

how it scales

The plot counts places weighed up on two maps: a line of places, each joined to the next, the run starting at one end, and every pair joined. nn is how many places, measured from 10 to 1,000.

Each mark across or up is ten times the one before. A line climbs one mark up for each mark across: 100 at 100 places and 1,000 at 1,000. Every pair joined climbs two marks up for each: 4,951 at 100 places and 499,501 at 1,000.

places weighed up, ten times more at each mark up

a seconda minutean houra dayslope 2102104106108101010121014101102103104105106107a seconda minutean houra dayslope 210110210310410510610710810910101011101210131014101102103104105106107a seconda minutean houra dayslope 210110210310410510610710810910101011101210131014101102103104105106107

nn, n, ten times more at each mark to the right

  • every pair joinedsolid where measured by running it; dashed where its formula carries it on to ten millionslope 2: ten times n, 100 times the work
  • a line, from one endsolid where measured by running it; dashed where its formula carries it on to ten million
how long every pair joined takes, at a billion places weighed up a second
nnplaces weighed uptime
1,000499,501about 500 microseconds
100,0004,999,950,001about 5 seconds
10,000,00049,999,995,000,001about 14 hours

The places weighed up are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.

make these counts yourself

Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.

"""Count Prim's places weighed up yourself, as the plot on this page does.

Run it with Python 3.12 or later. For each size n it runs two maps of n
places, from the first place, every length 1: a line, the fewest roads
that join them, and every two places joined, the most. It prints the
places weighed up for each, by count below, the method with a scan in
place of the heap. The counts are the same on any computer; only the
time differs.
"""
from heapq import heappop, heappush


def prim(roads, start):
    """Find the cheapest links that join every place start can reach.

    roads is a list of (place, place, length), each road running both
    ways. Returns the length written at each place joined: the road that
    joined it, and 0 at start. They add up to the links' total. A place
    no road leads to from start is left out.
    """
    return grow(neighbours(roads), start)[0]


def neighbours(roads):
    """Each place's roads, as pairs of the place at the far end and the length."""
    near = {}
    for a, b, length in roads:  # a road runs both ways
        near.setdefault(a, []).append((b, length))
        near.setdefault(b, []).append((a, length))
    return near


def grow(near, start):
    written = {start: 0}  # the start needs no road, so write 0 there
    came_from = {}  # the place each written road comes from
    joined = set()
    heap = [(0, start)]  # entries of length and place, cheapest on top
    while heap:  # none left: no place left has a road to the tree
        _, here = heappop(heap)  # the cheapest; on a tie, first in letter order
        if here in joined:  # an old entry: a cheaper one came first
            continue
        joined.add(here)  # join it, with the road written there
        for there, length in near.get(here, []):  # each road from it
            if there in joined:  # only to a place not in the tree
                continue
            if there not in written or length < written[there]:  # cheaper?
                written[there] = length  # write its length there
                came_from[there] = here
                heappush(heap, (length, there))
            # if not, keep the road written there
    return written, came_from


def cheapest_links(roads, start):
    """The roads joined, each as (place, place it came from), by letter."""
    _, came_from = grow(neighbours(roads), start)
    return sorted(came_from.items())


def count(roads, start):
    """How many places a scan weighs up: the method above with no heap,
    looking over every place with a road written and not in the tree."""
    near = neighbours(roads)
    written = {start: 0}
    joined = set()
    weighed = 0
    while True:
        waiting = [place for place in written if place not in joined]
        if not waiting:
            return weighed
        weighed += len(waiting)
        here = min(waiting, key=lambda place: (written[place], place))
        joined.add(here)
        for there, length in near.get(here, []):
            if there not in joined:
                if there not in written or length < written[there]:
                    written[there] = length


def line(n):
    """n places in a line, p0001 onward, each road 1 long: n - 1 roads."""
    return [(f"p{k:04}", f"p{k + 1:04}", 1) for k in range(1, n)]


def every_pair(n):
    """n places, every two joined, each road 1 long: n(n - 1) / 2 roads."""
    return [(f"p{a:04}", f"p{b:04}", 1) for a in range(1, n + 1) for b in range(a + 1, n + 1)]


if __name__ == "__main__":
    print(f"{'n':>6} {'a line':>8} {'every pair':>12}")
    for n in [10, 100, 1000]:
        print(f"{n:>6} {count(line(n), 'p0001'):>8} {count(every_pair(n), 'p0001'):>12}")

best, worst and average

This section takes maps in one piece, so every run joins every place. With 8 places, a line from one end weighs up 8, the town of eight from A 15, and every pair 29. The average is not worked out here.

A case is one kind of map, such as a line. A bound says how fast that case's cost grows as places are added.

The counts are in the grid. A count is often the sum of pieces that grow at different speeds, and on long inputs the fastest-growing piece swamps the rest. For example, a count of half of n times n, less half of n: at 2,000 items, 2,000,000 less 1,000. So how a cost grows is what tells one method from another, and the bounds keep just that.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
besta line, from one endworstevery pair joined
places weighed upnn, one place waiting in each round1+n(n−1)21 + \frac{n(n - 1)}{2}, all the rest waiting after round 1
roads looked alongn−1n - 1, each road oncen(n−1)2\frac{n(n - 1)}{2}, each road once
how the places weighed up grow in each case
tight, Θ\ThetaΘ(n)\Theta(n)Θ(n2)\Theta(n^2)
ceiling, OOO(n)O(n)O(n2)O(n^2)
floor, Ω\OmegaΩ(n)\Omega(n)Ω(n2)\Omega(n^2)

extra memory: A length, where it came from and a joined mark at each place. With a heap, also up to 1+m1 + m entries.

Extra memory is the room it needs on top of the input itself, while it runs.

1111ABCDE
A line of 5, from A. One place waits in each round.
1111ABCDE
A star of 5, from A in the middle, also 4 roads. Joining A writes a road at all 4 others.
rounda line of 5a star of 5every pair of 5
1111
2144
3133
4122
5111
all51111
Places weighed up in each round. Every pair of 5 has 10 roads, yet weighs up the same as the star.

where the formula comes from

Each count above, line by line, then why the links are cheapest.

Question 1: on a map in one piece, why does it look along each road once, mm roads in all?
  1. the move: each place joined once

    the line:
    each place isjoined once\begin{gathered} \text{each place is} \\ \text{joined once} \end{gathered}

    why it is allowed: Only places not joined yet are weighed up, so no place joins twice. On a map in one piece, while a place is left out, some road leaves the tree. Its far end holds a length, that road's or a cheaper one, so it waits, and its turn comes.

  2. the move: first end looks, second end skips

    the line:
    a road is looked alongfrom its end joined first\begin{gathered} \text{a road is looked along} \\ \text{from its end joined first} \end{gathered}
    426531728324ABCDEFGH
    The town of eight, 12 roads.
    place joinedroads it looks alonghow manyskips
    AA-B, A-E, A-F30
    EE-F11
    FF-B, F-G22
    BB-C12
    CC-D, C-G21
    GG-D, G-H22
    HH-D11
    Dnone03
    all1212
    The town of eight from A, in the order joined. Each road is looked along once and skipped once.

    why it is allowed: When one end joins, the other has not joined yet, so the road is looked along. When the other end joins later, the road leads to a joined place, so it is skipped.

  3. the move: one look for each road

    the line:
    L=1+1+⋯+1L = 1 + 1 + \dots + 1

    why it is allowed: LL is the roads looked along. By line 2 each of the mm roads gives one look.

  4. the move: add the ones

    the line:
    L=mL = m

    why it is allowed: mm ones make mm. For the town of eight, 12 roads, 12 looks.

try it with a small mm: at m=12m = 12, line 3 gives L=12L = 12, which you can work out by hand

Question 2: from one end, why does a line of nn places weigh up only nn, the fewest?
  1. the move: a line's roads

    the line:
    a line of n places:n−1 roads\begin{gathered} \text{a line of } n \text{ places:} \\ n - 1 \text{ roads} \end{gathered}

    why it is allowed: The first place needs no road, and each place after it adds one. By question 1, n−1n - 1 looks.

  2. the move: one place waits each round

    the line:
    K=1+1+⋯+1K = 1 + 1 + \dots + 1
    roundwaiting
    1A
    2B
    3C
    4D
    5E
    The line of 5 in section 3, from A.

    why it is allowed: KK is the places weighed up. From one end, joining a place writes a road only at the next, so one place waits in each round. Joining all nn takes nn rounds.

  3. the move: add the ones

    the line:
    K=nK = n

    why it is allowed: nn ones make nn. For 5 places, 5.

  4. the move: a ceiling

    the line:
    K≤nK \le n

    why it is allowed: By line 3, KK is nn, so it is at most nn.

  5. the move: read the bound

    the line:
    K∈O(n)K \in O(n)

    why it is allowed: By line 4, with the fixed multiple 1.

  6. the move: a floor

    the line:
    K≥nK \ge n

    why it is allowed: By line 3, KK is nn, so it is at least nn.

  7. the move: read the bound

    the line:
    K∈Ω(n)K \in \Omega(n)

    why it is allowed: By line 6, with the fixed multiple 1.

  8. the move: both together

    the line:
    K∈Θ(n)K \in \Theta(n)

    why it is allowed: Lines 5 and 7 bound KK by the same growth, nn.

  9. the move: no run weighs fewer

    the line:
    n rounds, eachweighing at least 1\begin{gathered} n \text{ rounds, each} \\ \text{weighing at least } 1 \end{gathered}

    why it is allowed: Each round weighs up the place it joins, so at least 1. A run that joins all nn has nn rounds, so it weighs up at least nn, which is KK by line 3.

try it with a small nn: at n=5n = 5, line 2 gives K=5K = 5, which you can work out by hand

Question 3: why does a map with every pair joined weigh up 1+n(n−1)21 + \frac{n(n - 1)}{2}, the most?
  1. the move: round by round

    the line:
    W=1+(n−1)+⋯+2+1W = 1 + (n - 1) + \dots + 2 + 1
    ABCDE
    Every pair of 5, from A, its lengths left out as they change nothing here.
    roundplaces waitingweighed up
    1A1
    2B, C, D, E4
    3C, D, E3
    4D, E2
    5E1
    all11
    Every pair of 5, every length 1, from A.

    why it is allowed: WW is the places weighed up. Round 1 weighs the start alone. It writes a road at the n−1n - 1 others, so round 2 weighs them all. From then on each round joins one, so the next weighs one fewer.

  2. the move: add up 1 to n - 1

    the line:
    W=1+n(n−1)2W = 1 + \frac{n(n - 1)}{2}
    where does this come from?
    question 2 of the page graphs and their wordsnn places, every two joined by a road. How many roads?
    1. the move: count place by place

      the line:
      R=(n−1)+⋯+2+1R = (n - 1) + \dots + 2 + 1
      ABCDE
      Every two of 5 places joined. A has 4 roads, B 3 more, C 2 more, D 1 more, E none new. 4 + 3 + 2 + 1 = 10.

      why it is allowed: Let RR be the roads, for 2 places or more. List the places. The first has roads to the n−1n - 1 after it. The next adds one fewer new road, as its road to the first is counted already. Each adds one fewer, and the last adds none.

    2. the move: use adding up 1 to n

      the line:
      R=n(n−1)2R = \frac{n(n - 1)}{2}
      placenew roads
      A4
      B3
      C2
      D1
      E0
      all10
      The new roads each place adds on line 1's map, in turn. 4 + 3 + 2 + 1 + 0 = 10.
      where does this come from?
      question 1 of the page adding up 1+2+⋯+n1 + 2 + \dots + nFit two staircases of squares together. What shape do they make?
      1. the move: draw the sum as a staircase

        the line:
        S=1+2+⋯+nS = 1 + 2 + \dots + n

        why it is allowed: Let SS be the sum of the whole numbers from 1 to nn. Draw it as a staircase, a column for each number: 1 square, then 2, and so on up to nn. For 5, columns of 1, 2, 3, 4 and 5 hold 15 squares.

      2. the move: take two staircases

        the line:
        2S=2(1+2+⋯+n)2S = 2(1 + 2 + \dots + n)

        why it is allowed: Two staircases hold twice the squares. Doubling both sides of line 1 keeps it true.

      3. the move: fit them into a rectangle

        the line:
        2S=n(n+1)2S = n(n + 1)
        Blue stands, yellow hangs. Two staircases of 1 to 5 squares fill a rectangle 5 wide and 6 tall, 30 squares. So 1 + 2 + 3 + 4 + 5 is 5 times 6, halved, which is 15.

        why it is allowed: Stand one staircase with its tallest column on the left. Hang the other upside down from the top, its tallest column on the right, as in the picture. The first column holds nn standing and 1 hanging. Each column to the right, the standing one loses a square and the hanging one gains one. So every column holds n+1n + 1, and the nn columns fill a rectangle nn wide and n+1n + 1 tall.

      4. the move: halve both sides

        the line:
        S=n(n+1)2S = \frac{n(n + 1)}{2}

        why it is allowed: Halving both sides of line 3 keeps it true and leaves one SS. For 5, half of 30 is 15.

      the whole page: adding up 1+2+⋯+n1 + 2 + \dots + n

      why it is allowed: Read from right to left, line 1 is 1 + 2 + up to n−1n - 1. The box under this line adds 1 up to a last number with two staircases, that number times one more, halved. Here the last number is n−1n - 1. One more than it is nn, so RR is n−1n - 1 times nn, halved. For 5, 1 + 2 + 3 + 4 is 4 times 5, halved, which is 10.

    3. the move: one way, each pair holds two

      the line:
      one way:U is twice R\begin{gathered} \text{one way:} \\ U \text{ is twice } R \end{gathered}

      why it is allowed: Let UU be the most one-way roads. A to B and B to A are two roads, one each way, so each pair holds two.

    4. the move: double line 2

      the line:
      U=2R=n(n−1)U = 2R = n(n - 1)

      why it is allowed: Line 3 says UU is 2R2R, and twice line 2 is n(n−1)n(n - 1). For 5 places, 20.

    5. the move: read it

      the line:
      5 places: 10 roads, or 20 one way1,000 places: 499,500 roads\begin{gathered} 5 \text{ places: 10 roads, or 20 one way} \\ 1{,}000 \text{ places: } 499{,}500 \text{ roads} \end{gathered}

      why it is allowed: 1,000 times 999, halved, is 499,500. A map of 1,000 places with 3,000 roads has 3 times as many roads as places, a few, so it is sparse. It holds 3,000 of the 499,500 it could.

    the whole page: graphs and their words

    why it is allowed: (n−1)+⋯+2+1(n - 1) + \dots + 2 + 1 is also how many roads every pair has: n(n−1)2\frac{n(n - 1)}{2}, shown under this line. For 3 places, 3 times 2, halved, is 3, and 1 + 3 is 4.

  3. the move: open the bracket

    the line:
    W=1+n2−n2W = 1 + \frac{n^2 - n}{2}

    why it is allowed: nn times n−1n - 1 is n2−nn^2 - n.

  4. the move: the fraction is at most half

    the line:
    W≤1+n22W \le 1 + \frac{n^2}{2}

    why it is allowed: By line 3. Taking nn away only lowers the fraction. For 3, 4 is at most 5.5.

  5. the move: 1 is at most half too

    the line:
    W≤n2W \le n^2

    why it is allowed: From 2 places on, 1 is at most half of n2n^2, and two halves make n2n^2. For 3, 4 is at most 9.

  6. the move: read the bound

    the line:
    W∈O(n2)W \in O(n^2)

    why it is allowed: By line 5, with the fixed multiple 1.

  7. the move: drop the 1

    the line:
    W≥n(n−1)2W \ge \frac{n(n - 1)}{2}

    why it is allowed: A floor needs a fixed part of n2n^2. Start from line 2, without its 1. For 3, 4 is at least 3.

  8. the move: halve n instead

    the line:
    W≥n2(n−1)W \ge \frac{n}{2}(n - 1)

    why it is allowed: The same product, with the halving on nn alone. For 3, 1.5 times 2 is 3.

  9. the move: n - 1 is at least half of n

    the line:
    W≥n2×n2W \ge \frac{n}{2} \times \frac{n}{2}

    why it is allowed: From 2 places on, 1 is at most half of nn, so taking it from nn leaves at least half. For 3, 2 is at least 1.5.

  10. the move: multiply the halves

    the line:
    W≥n24W \ge \frac{n^2}{4}

    why it is allowed: Half of nn times half of nn is a quarter of n2n^2. For 3, 4 is at least 2.25.

  11. the move: read the bound

    the line:
    W∈Ω(n2)W \in \Omega(n^2)

    why it is allowed: By line 10, with the fixed multiple a quarter.

  12. the move: both together

    the line:
    W∈Θ(n2)W \in \Theta(n^2)
    places weighed upplaces0204060801000246810places weighed upplaces0204060801000246810
    • n2n^2
    • WW
    • n24\frac{n^2}{4}
    WW stays between its floor and its ceiling.

    why it is allowed: Lines 6 and 11 bound WW by the same growth, n2n^2.

  13. the move: no run weighs more

    the line:
    any map of n places:at most W weighed up\begin{gathered} \text{any map of } n \text{ places:} \\ \text{at most } W \text{ weighed up} \end{gathered}

    why it is allowed: Round 1 weighs only the start. By round 2 one place is joined, so at most n−1n - 1 can wait. By round 3 two are, so one fewer, and so on. Line 1 adds up exactly those.

try it with a small nn: at n=3n = 3, line 1 gives W=4W = 4, which you can work out by hand

Question 4: with a scan, why do places joined, places weighed up and looks come to at most n2+1n^2 + 1?
  1. the move: three counts

    the line:
    Y=n+(1+n(n−1)2)+n(n−1)2\begin{gathered} Y = n + \left(1 + \frac{n(n - 1)}{2}\right) \\ + \frac{n(n - 1)}{2} \end{gathered}
    every pair of 5count
    places joined5
    places weighed up11
    roads looked along10
    the three together26
    26 is 5 times 5, plus 1.

    why it is allowed: YY is a run's work with every pair joined. It joins nn places, weighs up question 3's places, and looks along each road once, by question 1. Question 3's line 2 counts the roads.

  2. the move: two halves make a whole

    the line:
    Y=n+1+n(n−1)Y = n + 1 + n(n - 1)

    why it is allowed: Two halves of n(n−1)n(n - 1) make one. For 5, 5 + 1 + 20.

  3. the move: open the bracket

    the line:
    Y=n+1+n2−nY = n + 1 + n^2 - n

    why it is allowed: nn times n−1n - 1 is n2−nn^2 - n.

  4. the move: n and less n cancel

    the line:
    Y=n2+1Y = n^2 + 1

    why it is allowed: nn and less nn add to 0, leaving n2+1n^2 + 1. For 5, 26.

  5. the move: any map

    the line:
    any map: those threeat most n2+1\begin{gathered} \text{any map: those three} \\ \text{at most } n^2 + 1 \end{gathered}

    why it is allowed: Each of line 1's three is the most it can be. No run weighs up more, by question 3's last line. Two places share one road at most, so no map has more roads. No run joins more than nn.

  6. the move: add the skips

    the line:
    with skips:at most 2n2+1\begin{gathered} \text{with skips:} \\ \text{at most } 2n^2 + 1 \end{gathered}

    why it is allowed: Each road is skipped once at most, by question 1's line 2, and no map has more than n2n^2 roads. Add line 5.

  7. the move: add a program's reads

    the line:
    other reads too:at most 3n2+1\begin{gathered} \text{other reads too:} \\ \text{at most } 3n^2 + 1 \end{gathered}
    roundplaces readplaces waiting
    each of 551
    all255
    A line of 5 in a simple program. It reads 25, though only 5 are weighed up.

    why it is allowed: A simple program keeps no list of who waits, so each round it reads all nn places, at most n2n^2 reads. Add line 6.

  8. the move: read the bound

    the line:
    still O(n2),in books, O(V2)\begin{gathered} \text{still } O(n^2), \\ \text{in books, } O(V^2) \end{gathered}

    why it is allowed: By line 7, with the fixed multiple 4, as 1 is at most n2n^2. This is the cost of the scan the watch page draws.

try it with a small nn: at n=5n = 5, line 1 gives Y=26Y = 26, which you can work out by hand

Question 5: with a heap, why does a run's work grow no faster than m log⁡2 nm \,\log_2\, n?
  1. the move: a heap replaces the scan

    the line:
    the heap keepsthe cheapest on top\begin{gathered} \text{the heap keeps} \\ \text{the cheapest on top} \end{gathered}
    roundjoinspushesthe heap after, cheapest first
    startnoneA0A0
    1A0B9, E2E2, B9
    2E2F2F2, B9
    3F2B1B1, B9
    4B1C3C3, B9
    5C3noneB9
    The small map at the top, from A. E2 means E with a road of 2 written. B9 is an old entry, as B1 beat it.

    why it is allowed: Each new length goes in the heap as an entry, a push. To join, the top entry comes out, a pop, so no scan is needed. An old entry is passed by when it comes up.

  2. the move: count the pushes

    the line:
    J=1+mJ = 1 + m

    why it is allowed: JJ is the most pushes. The start goes in once. By question 1 each of the mm roads is looked along once, and a look pushes at most one entry.

  3. the move: count the pops

    the line:
    at most Jpops\begin{gathered} \text{at most } J \\ \text{pops} \end{gathered}

    why it is allowed: Only what went in can come out.

  4. the move: how high a heap stands

    the line:
    its height isat most  log⁡2 J\begin{gathered} \text{its height is} \\ \text{at most } \,\log_2\, J \end{gathered}

    why it is allowed: A heap fills each level before the next, 1 entry, then 2, then 4. Its height is its levels below the top. Height 1 takes at least 2 entries, height 2 takes 4, height 3 takes 8, doubling each time. By line 2 it holds at most JJ entries, so its height is at most log⁡2 J\log_2\, J.

  5. the move: each moves along one path

    the line:
    each push or pop:at most  log⁡2 J levels\begin{gathered} \text{each push or pop:} \\ \text{at most } \,\log_2\, J \text{ levels} \end{gathered}
    depth012124516789011425364758697012
    A heap of 7 entries, its height 2, each no bigger than those below it. A new entry in the last spot climbs the path marked while smaller than the one above.
    depth012426159078416253947586012
    The same heap after a pop. 1 comes out. The last entry, 9, goes on top and sinks past 4 and 6.

    why it is allowed: A level moved is one swap. A push starts in the last spot and climbs one path. A pop takes the top, puts the last entry there, and it sinks along one path. A path crosses at most the height, by line 4.

  6. the move: pushes by places

    the line:
    J is at most n2J \text{ is at most } n^2

    why it is allowed: By line 2, JJ is one more than the roads. Two places share one road at most, so no map has more roads than every pair. So JJ is at most question 3's WW, and its line 5 puts WW at most n2n^2. For the town, 13 is at most 64.

  7. the move: take logs of both sides

    the line:
    log⁡2 J is at most  log⁡2 n2\log_2\, J \text{ is at most } \,\log_2\, n^2

    why it is allowed: A bigger number has a bigger log⁡2\log_2.

  8. the move: the log of a square

    the line:
    log⁡2 J is at most 2 log⁡2 n\log_2\, J \text{ is at most } 2 \,\log_2\, n

    why it is allowed: n2n^2 is nn times nn. log⁡2 n\log_2\, n doublings from 1 reach nn, and as many again reach n2n^2. For 8, 3 doublings reach 8, and 3 more reach 64.

  9. the move: pushes and pops together

    the line:
    at most 2Jpushes and pops\begin{gathered} \text{at most } 2J \\ \text{pushes and pops} \end{gathered}

    why it is allowed: At most JJ pushes and JJ pops, by lines 2 and 3.

  10. the move: levels in all

    the line:
    at most4J log⁡2 n levels\begin{gathered} \text{at most} \\ 4J \,\log_2\, n \text{ levels} \end{gathered}

    why it is allowed: Line 9's 2J2J pushes and pops each cross at most 2 log⁡2 n2 \,\log_2\, n levels, by lines 5 and 8. Multiply. For the town, 4 times 13 times 3 is 156.

  11. the move: add joining and looks

    the line:
    at most4J log⁡2 n+n+m\begin{gathered} \text{at most} \\ 4J \,\log_2\, n + n + m \end{gathered}

    why it is allowed: Add nn places joined and mm looks.

  12. the move: both at most J

    the line:
    at most4J log⁡2 n+2J\begin{gathered} \text{at most} \\ 4J \,\log_2\, n + 2J \end{gathered}

    why it is allowed: In one piece, the tree's n−1n - 1 roads, by question 6's line 2, are among the mm. So nn is at most 1+m1 + m, which is JJ, and mm is below JJ.

  13. the move: give the lone part a log

    the line:
    at most4J log⁡2 n+2J log⁡2 n\begin{gathered} \text{at most} \\ 4J \,\log_2\, n + 2J \,\log_2\, n \end{gathered}

    why it is allowed: From 2 places on log⁡2 n\log_2\, n is at least 1, so 2J2J is at most 2J log⁡2 n2J \,\log_2\, n.

  14. the move: add the two

    the line:
    at most6J log⁡2 n\begin{gathered} \text{at most} \\ 6J \,\log_2\, n \end{gathered}

    why it is allowed: 4 lots and 2 lots make 6.

  15. the move: from pushes to roads

    the line:
    at most12m log⁡2 n\begin{gathered} \text{at most} \\ 12m \,\log_2\, n \end{gathered}

    why it is allowed: By line 2, JJ is 1+m1 + m, and from 1 road on 1+m1 + m is at most 2m2m. 6 times 2 is 12.

  16. the move: read the bound

    the line:
    levels, joining and looks inO(m log⁡2 n)in books, O(E log⁡2 V)\begin{gathered} \text{levels, joining and looks in} \\ O(m \,\log_2\, n) \\ \text{in books, } O(E \,\log_2\, V) \end{gathered}
    10210410610810101012101410161011021031041051061071011021031041051061071081091010101110121013101410151016101102103104105106107
    • the scan, n2n^2
    • the heap, 3 roads a place
    • the heap, every pair joined
    The ceilings' growth, fixed multiples left out.
    a map of 100 placesthe heapthe scan
    a line199299
    a star6005,150
    every pair, every length 15,45110,001
    every pair, every look writing65,63710,001
    Counted by running each, the heap popping as line 5 says, the line from one end, the star from its middle, every length 1 in the first three. Both count places joined and looks, the heap also levels moved, the scan also places weighed up. In the last, the first place's roads are all 99 long, the second's to later places all 98, and so on down to 1, so every look writes. A heap is not always quicker.

    why it is allowed: By line 15, with the fixed multiple 12, from 2 places on. Skips, at most mm, and a push or pop that moves no level, at most 2J2J, change only the multiple. So does the Python's heapq, whose pop can move up to twice as many levels.

  17. the move: which way to lean

    the line:
    few roads: the heap’sceiling grows slower;every pair: the scan’s\begin{gathered} \text{few roads: the heap's} \\ \text{ceiling grows slower;} \\ \text{every pair: the scan's} \end{gathered}

    why it is allowed: By line 16's plot, as maps grow. A ceiling says the most a run can cost, not what it does cost: in that line's table, every pair with every length 1, the heap still beats the scan.

try it with a small mm: at m=12m = 12, line 2 gives J=13J = 13, which you can work out by hand

Question 6: on a map in one piece, why does it join n−1n - 1 roads with no loop, and why does a cheapest network have n−1n - 1 too?
  1. the move: one road for each place but the start

    the line:
    R=1+1+⋯+1R = 1 + 1 + \dots + 1

    why it is allowed: RR is the roads joined. The start joins with none. By question 1's line 1 each of the other n−1n - 1 joins, with one.

  2. the move: add the ones

    the line:
    R=n−1R = n - 1

    why it is allowed: n−1n - 1 ones make n−1n - 1. For the town of eight, 7.

  3. the move: no loop

    the line:
    a road joined nevercloses a loop\begin{gathered} \text{a road joined never} \\ \text{closes a loop} \end{gathered}

    why it is allowed: Each road joined leads to a place not in the tree yet. A loop's last road would lead back to a place already in it.

  4. the move: a loop can lose a road

    the line:
    a cheapest networkhas no loop\begin{gathered} \text{a cheapest network} \\ \text{has no loop} \end{gathered}
    231ABE
    A loop of 3, costing 6. Take A to E off, and A still reaches E through B, costing 3.

    why it is allowed: Take any road off a loop. A trip that used it goes the other way round, so every place stays joined. Every length here is at least 1, so the cost falls. So a network with a loop is never cheapest.

  5. the move: n - 1 again

    the line:
    a cheapest networkhas n−1 roads\begin{gathered} \text{a cheapest network} \\ \text{has } n - 1 \text{ roads} \end{gathered}

    why it is allowed: Pick any place, and travel out from it along the network's roads. Each other place is first reached along one road, n−1n - 1 roads in all. Any other road would join two places already reached, closing a loop, and by line 4 there is none.

try it with a small nn: at n=8n = 8, line 1 gives R=7R = 7, which you can work out by hand

Question 7: on a map in one piece, why are the roads joined a cheapest network? Let ww be a network's cost, not question 3's WW, and TT its cost after one swap.
  1. the move: what stays true

    the line:
    the roads joined so far liein some cheapest network\begin{gathered} \text{the roads joined so far lie} \\ \text{in some cheapest network} \end{gathered}

    why it is allowed: Before round 2, no road is joined, so none can lie outside a cheapest network. The plan: show that joining the next road keeps this true.

  2. the move: split the places

    the line:
    the next road: cheapestacross the split\begin{gathered} \text{the next road: cheapest} \\ \text{across the split} \end{gathered}

    why it is allowed: Split the places into those in the tree and the rest. A road across has one end in each. Each place waiting holds its cheapest road from the tree, as a cheaper one always replaces what is written. So the next road joined, the cheapest written, is the cheapest across. On the small map, with A and E in the tree, B holds 9 and F holds 2.

  3. the move: swap a road on the loop

    the line:
    T=w−9+2T = w - 9 + 2
    29132ABCEF
    The network of 15 with E to F added. The loop, heavy, crosses the split on E to F and on A to B.

    why it is allowed: Take a network with A to E but without E to F: A to E, A to B, B to F and B to C. That costs 2 + 9 + 1 + 3, so ww is 15. Adding E to F closes a loop, which comes back across the split on A to B, of 9. Take A to B out.

  4. the move: add them up

    the line:
    T=w−7T = w - 7
    where does this come from?
    question 2 of the page greedy choices, and when they failSplit the places in two. Why does some cheapest network hold the cheapest road across? Let ww be a network's cost, and TT its cost after one swap.
    1. the move: swap a road on the loop

      the line:
      T=w−6+4T = w - 6 + 4
      36214ABCDE
      A network of 12, A to B, B to D, C to D and D to E, with A to C added. The loop A, C, D, B, A, heavy, crosses back on B to D, of 6.

      why it is allowed: The plan is to show a swap on a network that is not the cheapest, then use it on a cheapest one. Take a network without A to C, the cheapest road across. A to B, B to D, C to D and D to E cost 3 + 6 + 2 + 1, so here ww is 12. They already join A to C another way, so adding A to C closes a loop, roads leading round and back to A. The loop leaves the shaded group on A to C, so it comes back on another road across, B to D, of 6. Take B to D out.

    2. the move: add them up

      the line:
      T=w−2T = w - 2

      why it is allowed: Taking out 6 and putting in 4 is 2 less.

    3. the move: no dearer

      the line:
      T≤wT \le w
      3421ABCDE
      After the swap, B to D out and A to C in, at 12 less 2, which is 10.

      why it is allowed: ww less 2 is at most ww, so the swap costs no more. Before, 12; after, 10.

    4. the move: still one piece

      the line:
      every placestill joined\begin{gathered} \text{every place} \\ \text{still joined} \end{gathered}

      why it is allowed: A trip that used the road taken out goes the other way round the loop. From B to D, that is B, A, C, D.

    5. the move: on any map

      the line:
      cost after:w−f+e\begin{gathered} \text{cost after:} \\ w - f + e \end{gathered}

      why it is allowed: On any map, let ee be the cheapest road across, and ff a road where the loop crosses back. Each letter also stands for its road's length. Here ee is A to C, of 4, and ff is B to D, of 6. The swap takes ff out and puts ee in.

    6. the move: f costs at least e

      the line:
      w−f+eis at most w\begin{gathered} w - f + e \\ \text{is at most } w \end{gathered}

      why it is allowed: ff crosses too, and ee is the cheapest road across, so ff is at least ee. Taking ff out saves at least what putting ee in adds.

    7. the move: start from a cheapest one

      the line:
      a cheapest networkswaps to one with e\begin{gathered} \text{a cheapest network} \\ \text{swaps to one with } e \end{gathered}

      why it is allowed: The network of 12 only showed the swap. Start instead from a cheapest network without ee. The swap costs no more, and no network costs less than a cheapest one, so it costs the same. So it is cheapest too, and holds ee. A cheapest network that holds ee already needs no swap.

    the whole page: greedy choices, and when they fail

    why it is allowed: Taking out 9 and putting in 2 is 7 less. The proof of the swap on any map is under this line.

  5. the move: no dearer

    the line:
    T≤wT \le w

    why it is allowed: The road taken out crosses too, so it costs at least the cheapest across. Before, 15; after, 8.

  6. the move: roads joined stay

    the line:
    no road joinedis taken out\begin{gathered} \text{no road joined} \\ \text{is taken out} \end{gathered}

    why it is allowed: The road taken out crosses the split. A road joined has both ends in the tree, so it does not cross.

  7. the move: so it stays true

    the line:
    roads joined and the nextlie in a cheapest network\begin{gathered} \text{roads joined and the next} \\ \text{lie in a cheapest network} \end{gathered}
    111ABE
    All lengths 1, from A. A cheapest network, heavy, costs 2, and lacks A to B, the next road joined. Put A to B in and take A to E out: still 2.

    why it is allowed: The network of 15 only showed the swap. Start instead from a cheapest network holding the roads joined so far, by line 1. If it holds the next road too, nothing changes. If not, the swap leaves a network and costs no more, and no network costs less, so it is cheapest too. It holds the next road, and by line 6 it keeps the roads joined.

  8. the move: at the end

    the line:
    the links are acheapest network\begin{gathered} \text{the links are a} \\ \text{cheapest network} \end{gathered}

    why it is allowed: On a map in one piece, all nn places have joined, with n−1n - 1 roads, by question 6. They lie in a cheapest network, which also has n−1n - 1 roads. So they are all of it.

  9. the move: any start

    the line:
    any start givesthe same total\begin{gathered} \text{any start gives} \\ \text{the same total} \end{gathered}

    why it is allowed: Nothing above used which place came first, and all cheapest networks cost the same. On the town of eight, every start gives 18.

try it with a small ww: at w=15w = 15, line 3 gives T=8T = 8, which you can work out by hand

count it yourself

Count every place weighed up and every road looked along on every pair of 3 places: A, B and E. The watch page takes this map, from A, as A-B 2, A-E 5, B-E 1; A. E is first written 5, then beaten by B-E's 1. The last two columns are running totals. Places weighed up rise by 1 at step 2, 2 at step 4 and 1 at step 6.

A-B 2, A-E 5, B-E 1; A, every step written down
stepwhat happensroads looked alongplaces weighed up
1Start the tree at A. It needs no road to join, so write 0 there.00
2The road from A to B is 2 long, cheaper than any road to B found before. Write 2 at B.11
3The road from A to E is 5 long, cheaper than any road to E found before. Write 5 at E.21
4B has the cheapest road to the tree, 2 long from A. Join B with that road: the tree now has 2 of road.23
5The road from B to E is 1 long, cheaper than any road to E found before. Write 1 at E.33
6E has the cheapest road to the tree, 1 long from B. Join E with that road: the tree now has 3 of road.34
7Done: no place is left with a road to the tree. The cheapest links join the 3 places with 3 of road.34

In all, 4 places weighed up. The formula from section 4, 1+n(n−1)21 + \frac{n(n - 1)}{2}, gives W=4W = 4 at n=3n = 3: the same.

where you meet it

A 1957 paper tied finding a cheapest network to the rates for renting telephone lines. Ready-made code gives it to you, and it sits inside a way of sorting into groups.

  • Prim's 1957 paper

    Robert Prim, at Bell Telephone Laboratories, wrote it up, tying the problem to the rates for renting Bell's lines. Vojtech Jarnik had published the method in 1930, and Edsger Dijkstra gave it again in 1959.

    source: R. C. Prim, Shortest connection networks and some generalizations (opens in a new tab), Bell System Technical Journal 36(6); the three dates and Bell Labs, the books' volume three, chapter 31

  • networkx's prim_mst_edges

    networkx, ready-made Python code for maps of places and roads, offers this method for a cheapest network. It keeps roads in a heap, and passes by any whose far end has joined.

    source: the networkx source, mst.py (opens in a new tab), its prim_mst_edges

  • SciPy's single linkage

    SciPy, ready-made Python code for science, takes how far apart things are, every pair, and can sort them into groups, called single linkage. It looks over every place each round: the scan.

    source: the SciPy source, _hierarchy.pyx (opens in a new tab), its mst_single_linkage

what is used instead

When you want the shortest way between two places, use Dijkstra's method: section 7 draws why cheapest links do not give it. When the map may be in pieces, or the roads come in order of length, use Kruskal's method: a tree for each piece.

how it compares

Kruskal's method finds a cheapest network another way, one for each piece. Dijkstra's looks like Prim's, and answers another question.

methodpicks next byfinds
Prim's methodthe cheapest road from the treea cheapest network of the start's piece
Kruskal's methodthe cheapest road left, unless it closes a loopa cheapest network for each piece
Dijkstra's methodthe least total length from the startshortest ways from the start
On the small map at the top, Kruskal's takes 1, 2, 2 and 3, and leaves the 9, which would close a loop: 8, as Prim's.
221ABE
Prim's links from A, heavy, 3 in all. Along them, A to E is 3.
221ABE
The shortest way from A to E, heavy, 2, on a road the links leave out.

race them on one row of your own