C - 荷物の回収 / Luggage Collection Editorial by admin Editorial for printing
DeepSeek V3Overview
This problem asks for the minimum total travel distance when collecting packages from multiple delivery destinations along a straight road from a distribution center. At most M packages can be collected in a single round trip, and the travel distance for each round trip is twice the distance to the farthest destination visited.
Analysis
The two key observations are:
- Only distances matter: The destination numbers are irrelevant; only the distances from the distribution center affect the travel distance.
- Optimal route selection: We need to efficiently group the farthest destinations together for collection.
A naive approach that considers all possible combinations of packages leads to combinatorial explosion, making it infeasible since \(K\) can be as large as 200,000.
An efficient solution is to sort by distance and then greedily group destinations into sets of M, starting from the farthest. This works because splitting the collection of far destinations across multiple trips would mean traveling the same long distance multiple times, which is inefficient.
Algorithm
- Store all destination distances in a list and sort in ascending order.
- If \(M \geq K\) (all packages can be collected in one trip), the answer is twice the maximum distance.
- Otherwise:
- Group destinations into sets of M, starting from the farthest.
- For each group, add twice the distance of the farthest destination in that group to the total.
- Repeat until all packages have been collected.
Specifically, starting from the right end (maximum distance) of the sorted array, we move leftward, skipping M elements at a time, and accumulate twice the maximum distance of each group.
Complexity
- Time complexity: \(O(K \log K)\) (dominated by sorting)
- Space complexity: \(O(K)\) (for storing destination distances)
Implementation Notes
When parsing input data, destination numbers are unnecessary; only distances need to be stored in the list.
Using
right -= mto advance through groups of M enables efficient computation.Don’t forget to handle the boundary condition (when \(M \geq K\)).
Source Code
import sys
def main():
data = sys.stdin.read().split()
if not data:
return
n = int(data[0])
k = int(data[1])
m = int(data[2])
deliveries = []
index = 3
for i in range(k):
b = int(data[index])
d = int(data[index+1])
index += 2
deliveries.append(d)
deliveries.sort()
if m >= k:
total = 2 * deliveries[-1]
print(total)
return
left = 0
right = k - 1
total_distance = 0
while right >= left:
farthest = deliveries[right]
total_distance += 2 * farthest
right -= m
print(total_distance)
if __name__ == "__main__":
main()
This editorial was generated by deepseekv3.
posted:
last update: