❓ The question first
❓ THE QUESTION
Problem — Are We There Yet?
You drive along a very straight road past five cities, recording the distance between each pair of consecutive cities. Build the full distance table: the distance between any two of the cities.
Input
One line with 4 positive integers: the distances between consecutive cities (city 1–2, 2–3, 3–4, 4–5).
3 10 12 5
Output
5 lines. Line i holds the distances from city i to cities 1, 2, 3, 4, 5, separated by spaces.
0 3 13 25 30 3 0 10 22 27 13 10 0 12 17 25 22 12 0 5 30 27 17 5 0
🎬 The solution, step by step
The idea — addresses first, distances second:
- Turn each city into a number: its distance from City 1, built by a running total (prefix sum).
- After that, the distance between any two cities is just
|address[i] − address[j]|. - Print the 5 × 5 table of those subtractions.
Animation — walk the official sample
💻 The code
d = list(map(int, input().split())) pos = [0] # address of City 1 for gap in d: pos.append(pos[-1] + gap) # prefix sums: 0, 3, 13, 25, 30 for i in range(5): row = [abs(pos[i] - pos[j]) for j in range(5)] print(*row) # *row prints with spaces
⭐ Key points & traps
The one-line insight: never add gaps pair by pair (that is 25 little journeys). Build the address list once; every answer is then a single subtraction.
Trap — forgetting the absolute value: city 4 → city 2 is 3 − 25 = −22 without
abs(...). Distances are never negative; abs is what makes the table symmetric.Pattern to remember: “distance along a line from gap measurements” = prefix sums. This same running-total idea returns in Sum Game (2017) and Snail Path (2026).
✋ Your turn — predict first, then check
Input 5 5 5 5 — what is row 1 of the output? And the distance from City 2 to City 5?
Addresses: 0, 5, 10, 15, 20. Row 1: 0 5 10 15 20. City 2 → City 5 = |5 − 20| = 15.