#C2831. Minimum Total Travel Distance
Minimum Total Travel Distance
Minimum Total Travel Distance
You are given a series of positions on a number line. Each position represents a destination where a robot must deliver a package. The robots can start from any arbitrary point and the goal is to minimize the total travel distance required for all deliveries.
The optimal strategy is to choose a meeting point that minimizes the sum of the distances from each given position, which is achieved by selecting the median of the positions. When the number of positions is even, choosing any point between the two middle elements minimizes the total distance; for consistency, we choose the upper median (i.e. the element at index n/2 after sorting the positions).
Your task is to compute the minimum total distance that all robots must travel, given the list of positions. If there are no positions, the answer is 0.
The formula for the total distance can be expressed as:
\[ D = \sum_{i=1}^{n} |x_i - m|, \]where \(m\) is the median of the list \(\{x_1, x_2, \dots, x_n\}\). For an empty array, define the total distance as 0.
inputFormat
The first line contains a single integer \(n\) representing the number of positions.
If \(n > 0\), the second line contains \(n\) space-separated integers representing the positions on the number line. If \(n = 0\), the second line is omitted.
outputFormat
Output a single integer which is the minimum total distance that all robots need to travel.
## sample0
0