SPAN-P2

The cheapest network

Practice 2 of 4Minimum spanning trees9 tests

The problem

Choose lines from edges so that every station can reach every other, and the total cost is as small as possible: a minimum spanning tree. Return the chosen lines as a list of (u, v, w) triples, exactly as they appear in edges (either way round). Return None if the stations cannot all be joined.

edges = [(0, 1, 4), (0, 3, 2), (1, 3, 5), (1, 2, 6),
         (1, 4, 3), (3, 4, 7), (2, 4, 8), (2, 5, 1),
         (4, 5, 9), (2, 6, 5), (5, 6, 7)]
mst(7, edges)
# [(2, 5, 1), (0, 3, 2), (1, 4, 3), (0, 1, 4),
#  (2, 6, 5), (1, 2, 6)]   total 21

When several trees cost the least, any of them is accepted. The tests check that your lines are taken from the list, that there are n − 1 of them with no loop, and that their total is the least. Costs are whole numbers and may be negative. A line may join a station to itself, and two stations may be joined by more than one line.

Limits

  • Up to 100,000 stations and 250,000 lines.
  • Joining two groups must be fast: relabelling every station of a group each time is too slow. The big tests have 4 seconds each.

Builds on SPAN-2 Kruskal.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

9 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2TiesNot run
3Not connectedNot run
4One stationNot run
5Loops and repeated linesNot run
6Negative costsNot run
71,000 stationsNot run
8100,000 stations, 250,000 linesNot run
9A chain of 100,000, in orderNot run