C - 荷物の回収 / Luggage Collection Editorial by admin Editorial for printing
gemini-3.1-pro-thinkingOverview
This problem asks for the minimum total travel distance when collecting \(K\) packages at destinations on a line, using a truck that can carry at most \(M\) packages at a time.
Analysis
The travel distance for a single round trip equals twice the distance to the farthest destination visited during that trip. In other words, while going to collect a distant package, you can pick up at most \(M-1\) additional packages that are closer at no extra cost.
How should we minimize the total travel distance? To collect the farthest package (at distance \(D_{\max}\)), a round trip of distance \(2D_{\max}\) is unavoidable. At this point, using the truck’s remaining capacity to also collect the “next farthest packages” is the most efficient approach. Packages that are closer can be left for later, since they can be collected with shorter round trips.
Therefore, the optimal strategy is a greedy approach: sort all packages by distance from the distribution center in descending order, and collect them in groups of \(M\), starting from the farthest.
Algorithm
- Extract the distances \(D_1, D_2, \dots, D_K\) of the destinations where packages need to be collected. Note that the total number of destinations \(N\) and destination numbers \(B_i\) do not affect the answer and can be ignored.
- Sort the distance array \(D\) in descending order.
- To group packages in sets of \(M\) starting from the farthest, take every \(M\)-th element from the beginning of the sorted array (elements at indices \(0, M, 2M, \dots\)). These represent the “farthest destination distance” for each round trip.
- The answer is twice the sum of the extracted distances, which gives the minimum total travel distance.
Complexity
- Time complexity: \(O(K \log K)\) The bottleneck is sorting the distance array. Since \(K \leq 2 \times 10^5\), this runs well within the time limit.
- Space complexity: \(O(K)\) Memory is needed to store the \(K\) input distance values.
Implementation Tips
Using slicing: In Python, the list slicing feature
D[::M]provides a very concise way to extract every \(M\)-th element from the beginning.Fast I/O: Since the input data can be large, using
sys.stdin.read().split()to read all input at once is faster than callinginput()in a loop. Combined with list comprehensions, this allows efficient extraction of only the needed data (distances \(D_i\)).Source Code
import sys
def main():
input_data = sys.stdin.read().split()
if not input_data:
return
K = int(input_data[1])
M = int(input_data[2])
D = [int(input_data[4 + 2 * i]) for i in range(K)]
D.sort(reverse=True)
ans = sum(D[::M]) * 2
print(ans)
if __name__ == '__main__':
main()
This editorial was generated by gemini-3.1-pro-thinking.
posted:
last update: