SPAN-P1

A cheaper line

Practice 1 of 4Minimum spanning trees11 tests

The problem

A railway has n stations joined by a spanning tree of lines: tree holds n − 1 lines (u, v, w), each costing w a year to run, and together they join every station with no loop. A new line extra = (a, b, w) is offered. Using the old lines and the new one, which lines should run to join every station as cheaply as possible? Return the total yearly cost of that cheapest spanning tree.

tree = [(0, 1, 4), (1, 2, 2), (1, 3, 7), (3, 4, 1)]
cheaper_tree(5, tree, (2, 3, 3))   # 10
cheaper_tree(5, tree, (0, 4, 9))   # 14

In the first call, the new line closes the loop 2 → 1 → 3 → 2. Dropping the line 1–3, which costs 7, gives 14 − 7 + 3 = 10. Costs are whole numbers and may be negative. The new line may join a station to itself, or two stations already joined by a line.

Limits

  • Up to 100,000 stations.
  • The tree can be a path 100,000 stations long, so a recursive search is too deep. The big tests have 3 seconds each.

Builds on SPAN-1 Spanning trees.

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.

11 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2The new line is too expensiveNot run
3The most expensive line is elsewhereNot run
4Exactly as expensiveNot run
5A line from a station to itselfNot run
6Beside a tree lineNot run
7Negative costsNot run
8One stationNot run
9A path of 100,000Not run
10A random tree of 100,000Not run
11Many lines at the same costNot run