Prim's cheapest links
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.
| round | waiting | joins | looks along | writes |
|---|---|---|---|---|
| 1 | A 0 | A | A-B, A-E | B 9, E 2 |
| 2 | B 9, E 2 | E by A-E | E-F | F 2 |
| 3 | B 9, F 2 | F by E-F | F-B | B 1, beating 9 |
| 4 | B 1 | B by F-B | B-C | C 3 |
| 5 | C 3 | C by B-C | none | none |
step 1 of 21
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.
step 4 of 21
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
step 5 of 21
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
step 8 of 21
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
step 10 of 21
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
step 14 of 21
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
step 19 of 21
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
step 21 of 21
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.
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- start the tree at the start: it needs no road, so write 0 therePython line 25
- join the place not in the tree with the cheapest road to it, and that roadPython lines 30, 31, 32 and 33
- look along each road from it to a place not in the treePython lines 34, 35 and 36
- if it is cheaper than the road written there, write its length therePython lines 37, 38, 39 and 40
- if not, keep the road written therePython line 41
- 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. 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
, 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
| places weighed up | time | |
|---|---|---|
| 1,000 | 499,501 | about 500 microseconds |
| 100,000 | 4,999,950,001 | about 5 seconds |
| 10,000,000 | 49,999,995,000,001 | about 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.
| besta line, from one end | worstevery pair joined | |
|---|---|---|
| places weighed up | , one place waiting in each round | , all the rest waiting after round 1 |
| roads looked along | , each road once | , each road once |
| how the places weighed up grow in each case | ||
| tight, | ||
| ceiling, | ||
| floor, | ||
extra memory: A length, where it came from and a joined mark at each place. With a heap, also up to entries.
Extra memory is the room it needs on top of the input itself, while it runs.
| round | a line of 5 | a star of 5 | every pair of 5 |
|---|---|---|---|
| 1 | 1 | 1 | 1 |
| 2 | 1 | 4 | 4 |
| 3 | 1 | 3 | 3 |
| 4 | 1 | 2 | 2 |
| 5 | 1 | 1 | 1 |
| all | 5 | 11 | 11 |
where the formula comes from
Each count above, line by line, then why the links are cheapest.
the move: each place joined once
the line: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.
the move: first end looks, second end skips
the line:The town of eight, 12 roads. place joined roads it looks along how many skips A A-B, A-E, A-F 3 0 E E-F 1 1 F F-B, F-G 2 2 B B-C 1 2 C C-D, C-G 2 1 G G-D, G-H 2 2 H H-D 1 1 D none 0 3 all 12 12 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.
guess it, thenthe move: one look for each road
the line:why it is allowed: is the roads looked along. By line 2 each of the roads gives one look.
guess it, thenthe move: add the ones
the line:why it is allowed: ones make . For the town of eight, 12 roads, 12 looks.
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
the move: a line's roads
the line:why it is allowed: The first place needs no road, and each place after it adds one. By question 1, looks.
the move: one place waits each round
the line:round waiting 1 A 2 B 3 C 4 D 5 E The line of 5 in section 3, from A. why it is allowed: 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 takes rounds.
guess it, thenthe move: add the ones
the line:why it is allowed: ones make . For 5 places, 5.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 3, is , so it is at most .
guess it, thenthe move: read the bound
the line:why it is allowed: By line 4, with the fixed multiple 1.
guess it, thenthe move: a floor
the line:why it is allowed: By line 3, is , so it is at least .
guess it, thenthe move: read the bound
the line:why it is allowed: By line 6, with the fixed multiple 1.
guess it, thenthe move: both together
the line:why it is allowed: Lines 5 and 7 bound by the same growth, .
guess it, thenthe move: no run weighs fewer
the line:why it is allowed: Each round weighs up the place it joins, so at least 1. A run that joins all has rounds, so it weighs up at least , which is by line 3.
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
the move: round by round
the line:Every pair of 5, from A, its lengths left out as they change nothing here. round places waiting weighed up 1 A 1 2 B, C, D, E 4 3 C, D, E 3 4 D, E 2 5 E 1 all 11 Every pair of 5, every length 1, from A. why it is allowed: is the places weighed up. Round 1 weighs the start alone. It writes a road at the others, so round 2 weighs them all. From then on each round joins one, so the next weighs one fewer.
the move: add up 1 to n - 1
the line:where does this come from?
question 2 of the page graphs and their words places, every two joined by a road. How many roads? the move: count place by place
the line: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 be the roads, for 2 places or more. List the places. The first has roads to the 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.
the move: use adding up 1 to n
the line:place new roads A 4 B 3 C 2 D 1 E 0 all 10 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 Fit two staircases of squares together. What shape do they make? the move: draw the sum as a staircase
the line:why it is allowed: Let be the sum of the whole numbers from 1 to . Draw it as a staircase, a column for each number: 1 square, then 2, and so on up to . For 5, columns of 1, 2, 3, 4 and 5 hold 15 squares.
the move: take two staircases
the line:why it is allowed: Two staircases hold twice the squares. Doubling both sides of line 1 keeps it true.
the move: fit them into a rectangle
the line: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 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 , and the columns fill a rectangle wide and tall.
the move: halve both sides
the line:why it is allowed: Halving both sides of line 3 keeps it true and leaves one . For 5, half of 30 is 15.
why it is allowed: Read from right to left, line 1 is 1 + 2 + up to . 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 . One more than it is , so is times , halved. For 5, 1 + 2 + 3 + 4 is 4 times 5, halved, which is 10.
the move: one way, each pair holds two
the line:why it is allowed: Let be the most one-way roads. A to B and B to A are two roads, one each way, so each pair holds two.
the move: double line 2
the line:why it is allowed: Line 3 says is , and twice line 2 is . For 5 places, 20.
the move: read it
the line: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.
why it is allowed: is also how many roads every pair has: , shown under this line. For 3 places, 3 times 2, halved, is 3, and 1 + 3 is 4.
guess it, thenthe move: open the bracket
the line:why it is allowed: times is .
guess it, thenthe move: the fraction is at most half
the line:why it is allowed: By line 3. Taking away only lowers the fraction. For 3, 4 is at most 5.5.
guess it, thenthe move: 1 is at most half too
the line:why it is allowed: From 2 places on, 1 is at most half of , and two halves make . For 3, 4 is at most 9.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 5, with the fixed multiple 1.
guess it, thenthe move: drop the 1
the line:why it is allowed: A floor needs a fixed part of . Start from line 2, without its 1. For 3, 4 is at least 3.
guess it, thenthe move: halve n instead
the line:why it is allowed: The same product, with the halving on alone. For 3, 1.5 times 2 is 3.
guess it, thenthe move: n - 1 is at least half of n
the line:why it is allowed: From 2 places on, 1 is at most half of , so taking it from leaves at least half. For 3, 2 is at least 1.5.
guess it, thenthe move: multiply the halves
the line:why it is allowed: Half of times half of is a quarter of . For 3, 4 is at least 2.25.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 10, with the fixed multiple a quarter.
guess it, thenthe move: both together
the line:stays between its floor and its ceiling. why it is allowed: Lines 6 and 11 bound by the same growth, .
guess it, thenthe move: no run weighs more
the line:why it is allowed: Round 1 weighs only the start. By round 2 one place is joined, so at most can wait. By round 3 two are, so one fewer, and so on. Line 1 adds up exactly those.
guess it, then
try it with a small : at , line 1 gives , which you can work out by hand
the move: three counts
the line:every pair of 5 count places joined 5 places weighed up 11 roads looked along 10 the three together 26 26 is 5 times 5, plus 1. why it is allowed: is a run's work with every pair joined. It joins places, weighs up question 3's places, and looks along each road once, by question 1. Question 3's line 2 counts the roads.
the move: two halves make a whole
the line:why it is allowed: Two halves of make one. For 5, 5 + 1 + 20.
guess it, thenthe move: open the bracket
the line:why it is allowed: times is .
guess it, thenthe move: n and less n cancel
the line:why it is allowed: and less add to 0, leaving . For 5, 26.
guess it, thenthe move: any map
the line: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 .
guess it, thenthe move: add the skips
the line:why it is allowed: Each road is skipped once at most, by question 1's line 2, and no map has more than roads. Add line 5.
guess it, thenthe move: add a program's reads
the line:round places read places waiting each of 5 5 1 all 25 5 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 places, at most reads. Add line 6.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 7, with the fixed multiple 4, as 1 is at most . This is the cost of the scan the watch page draws.
guess it, then
try it with a small : at , line 1 gives , which you can work out by hand
the move: a heap replaces the scan
the line:round joins pushes the heap after, cheapest first start none A0 A0 1 A0 B9, E2 E2, B9 2 E2 F2 F2, B9 3 F2 B1 B1, B9 4 B1 C3 C3, B9 5 C3 none B9 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.
the move: count the pushes
the line:why it is allowed: is the most pushes. The start goes in once. By question 1 each of the roads is looked along once, and a look pushes at most one entry.
guess it, thenthe move: count the pops
the line:why it is allowed: Only what went in can come out.
guess it, thenthe move: how high a heap stands
the line: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 entries, so its height is at most .
guess it, thenthe move: each moves along one path
the line: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. 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.
guess it, thenthe move: pushes by places
the line:why it is allowed: By line 2, is one more than the roads. Two places share one road at most, so no map has more roads than every pair. So is at most question 3's , and its line 5 puts at most . For the town, 13 is at most 64.
guess it, thenthe move: take logs of both sides
the line:why it is allowed: A bigger number has a bigger .
guess it, thenthe move: the log of a square
the line:why it is allowed: is times . doublings from 1 reach , and as many again reach . For 8, 3 doublings reach 8, and 3 more reach 64.
guess it, thenthe move: pushes and pops together
the line:why it is allowed: At most pushes and pops, by lines 2 and 3.
guess it, thenthe move: levels in all
the line:why it is allowed: Line 9's pushes and pops each cross at most levels, by lines 5 and 8. Multiply. For the town, 4 times 13 times 3 is 156.
guess it, thenthe move: add joining and looks
the line:why it is allowed: Add places joined and looks.
guess it, thenthe move: both at most J
the line:why it is allowed: In one piece, the tree's roads, by question 6's line 2, are among the . So is at most , which is , and is below .
guess it, thenthe move: give the lone part a log
the line:why it is allowed: From 2 places on is at least 1, so is at most .
guess it, thenthe move: add the two
the line:why it is allowed: 4 lots and 2 lots make 6.
guess it, thenthe move: from pushes to roads
the line:why it is allowed: By line 2, is , and from 1 road on is at most . 6 times 2 is 12.
guess it, thenthe move: read the bound
the line:- the scan,
- the heap, 3 roads a place
- the heap, every pair joined
The ceilings' growth, fixed multiples left out. a map of 100 places the heap the scan a line 199 299 a star 600 5,150 every pair, every length 1 5,451 10,001 every pair, every look writing 65,637 10,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 , and a push or pop that moves no level, at most , change only the multiple. So does the Python's heapq, whose pop can move up to twice as many levels.
guess it, thenthe move: which way to lean
the line: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.
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
the move: one road for each place but the start
the line:why it is allowed: is the roads joined. The start joins with none. By question 1's line 1 each of the other joins, with one.
the move: add the ones
the line:why it is allowed: ones make . For the town of eight, 7.
guess it, thenthe move: no loop
the line: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.
guess it, thenthe move: a loop can lose a road
the line: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.
guess it, thenthe move: n - 1 again
the line: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, roads in all. Any other road would join two places already reached, closing a loop, and by line 4 there is none.
guess it, then
try it with a small : at , line 1 gives , which you can work out by hand
the move: what stays true
the line: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.
the move: split the places
the line: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.
guess it, thenthe move: swap a road on the loop
the line: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 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.
guess it, thenthe move: add them up
the line: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 be a network's cost, and its cost after one swap. the move: swap a road on the loop
the line: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 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.
the move: add them up
the line:why it is allowed: Taking out 6 and putting in 4 is 2 less.
the move: no dearer
the line:After the swap, B to D out and A to C in, at 12 less 2, which is 10. why it is allowed: less 2 is at most , so the swap costs no more. Before, 12; after, 10.
the move: still one piece
the line: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.
the move: on any map
the line:why it is allowed: On any map, let be the cheapest road across, and a road where the loop crosses back. Each letter also stands for its road's length. Here is A to C, of 4, and is B to D, of 6. The swap takes out and puts in.
the move: f costs at least e
the line:why it is allowed: crosses too, and is the cheapest road across, so is at least . Taking out saves at least what putting in adds.
the move: start from a cheapest one
the line:why it is allowed: The network of 12 only showed the swap. Start instead from a cheapest network without . 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 . A cheapest network that holds already needs no swap.
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.
guess it, thenthe move: no dearer
the line:why it is allowed: The road taken out crosses too, so it costs at least the cheapest across. Before, 15; after, 8.
guess it, thenthe move: roads joined stay
the line: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.
guess it, thenthe move: so it stays true
the line: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.
guess it, thenthe move: at the end
the line:why it is allowed: On a map in one piece, all places have joined, with roads, by question 6. They lie in a cheapest network, which also has roads. So they are all of it.
guess it, thenthe move: any start
the line: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.
guess it, then
try it with a small : at , line 3 gives , 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.
| step | what happens | roads looked along | places weighed up |
|---|---|---|---|
| 1 | Start the tree at A. It needs no road to join, so write 0 there. | 0 | 0 |
| 2 | The road from A to B is 2 long, cheaper than any road to B found before. Write 2 at B. | 1 | 1 |
| 3 | The road from A to E is 5 long, cheaper than any road to E found before. Write 5 at E. | 2 | 1 |
| 4 | B has the cheapest road to the tree, 2 long from A. Join B with that road: the tree now has 2 of road. | 2 | 3 |
| 5 | The road from B to E is 1 long, cheaper than any road to E found before. Write 1 at E. | 3 | 3 |
| 6 | E has the cheapest road to the tree, 1 long from B. Join E with that road: the tree now has 3 of road. | 3 | 4 |
| 7 | Done: no place is left with a road to the tree. The cheapest links join the 3 places with 3 of road. | 3 | 4 |
In all, 4 places weighed up. The formula from section 4, , gives at : 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.
| method | picks next by | finds |
|---|---|---|
| Prim's method | the cheapest road from the tree | a cheapest network of the start's piece |
| Kruskal's method | the cheapest road left, unless it closes a loop | a cheapest network for each piece |
| Dijkstra's method | the least total length from the start | shortest ways from the start |