ADDP-P1

Total distance from every station

Practice 1 of 6Advanced DP11 tests

The problem

A railway company has n stations joined by n − 1 roads, so that there is exactly one way between any two stations: the roads form a tree. Each road is given as (u, v, length), in either direction. For every station, return the total of its distances to all the other stations.

total_distance(4, [(0, 1, 1), (1, 2, 1), (2, 3, 1)])
# [6, 4, 4, 6]
total_distance(3, [(0, 1, 2), (1, 2, 10)])   # [14, 12, 22]

Limits

  • Up to 100,000 stations; lengths from 0 to 1,000.
  • The tree can be a single line of 100,000 stations, so a recursive search runs out of depth.
  • A search from every station takes about 10¹⁰ steps. Aim for O(n).

Builds on ADDP-1 DP on 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
1One stationNot run
2Two stationsNot run
3A line of fourNot run
4Lengths matterNot run
5A starNot run
6Roads listed the other way roundNot run
7A road of length 0Not run
8The figure's tree, with lengthsNot run
9A long lineNot run
10100,000 stations, randomNot run
11A broomNot run