Pair Workers With Distinct Stations at Minimum Grid Distance
Dynamic ProgrammingAuto-graded · 25 test casesLast updated
Match each point in one list to a different point in a larger list so the total Manhattan distance is minimal, which suits a bitmask DP given the small limits.
Pair Workers With Distinct Stations at Minimum Grid Distance
A grid contains n workers and m charging stations, with n <= m. Every worker has to be sent to a station, and no two workers may share the same station. Some stations may end up unused.
Each worker and each station is described by integer coordinates [x, y]. Sending a worker at (x1, y1) to a station at (x2, y2) costs the Manhattan distance:
|x1 - x2| + |y1 - y2|
Write a function that returns the smallest possible sum of costs over all workers, considering every valid way of giving each worker its own station.
Input
workers: a list ofnpairs[x, y], the worker positions.stations: a list ofmpairs[x, y], the station positions.
Output
An integer: the minimum total cost of a valid assignment.
Notes
- Several workers or stations may share the same coordinates. Coordinates may be negative.
- Choosing the nearest station for each worker one by one is not guaranteed to be optimal.
Constraints
1 <= n <= 10n <= m <= 15- Each coordinate is an integer.
- Every worker must receive exactly one station, and each station is used by at most one worker.
Examples
Example 1
Input: min_total_pairing_distance([[0, 0], [2, 1]], [[1, 0], [2, 2], [5, 5]])
Output: 2
Example 2
Input: min_total_pairing_distance([[0, 0]], [[3, 4]])
Output: 7
Example 3
Input: min_total_pairing_distance([[0, 0], [10, 10]], [[1, 1], [9, 9]])
Output: 4
Hints
Hint 1
Trying all injective assignments means up to 15!/5! possibilities, which is far too many. Look for repeated subproblems.
Hint 2
If you handle workers in index order, the set of stations already taken is enough to tell you how many workers are placed and which one comes next. Use a bitmask over the stations.
Hint 3
Let dp[mask] be the cheapest cost of serving the first popcount(mask) workers using exactly the stations in mask. Extend each state by one unused station, and take the minimum over masks with exactly n bits set.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Process workers in index order: worker 0, then worker 1, and so on. Under this convention, a bitmask over the m stations describes a whole partial state:
- The number of set bits
kis how many workers have been placed, and they are exactly workers0..k-1. - The set bits are the stations they occupy.
Define dp[mask] as the minimum cost of assigning workers 0..k-1 to exactly the stations in mask, where k is the number of set bits.
- Base:
dp[0] = 0. - Transition: for a mask with
k < nbits, the next worker is workerk. For every stationjnot in the mask, updatedp[mask | (1 << j)]withdp[mask] + dist(worker k, station j). - Answer: the minimum of
dp[mask]over all masks with exactlynbits set. Unused stations are simply the bits left at zero.
Why it is correct
- Every valid assignment corresponds to a path of transitions: add the stations chosen for workers 0, 1, ..., n-1 in that order. The path's cost equals the assignment's cost.
- Every path of transitions is a valid assignment, because each step gives the next worker a station not yet used.
- The cost of completing an assignment depends only on which stations remain free and which workers remain, and the latter is determined by the popcount. Keeping only the minimum per mask therefore discards nothing useful.
- Adding a bit increases the integer value of a mask, so iterating masks in increasing order processes every state before the states it feeds.
A greedy nearest-station choice is wrong, since an early worker taking its closest station can force a later worker into a much worse one.
Complexity
- Time:
O(2^m * m), about 500 thousand transitions atm = 15. - Space:
O(2^m)for the DP table.
Reference solution
from typing import List
def min_total_pairing_distance(workers: List[List[int]], stations: List[List[int]]) -> int:
n = len(workers)
m = len(stations)
inf = float('inf')
dp = [inf] * (1 << m)
dp[0] = 0
for mask in range(1 << m):
placed = bin(mask).count("1")
if placed >= n or dp[mask] == inf:
continue
wx, wy = workers[placed]
for j in range(m):
if not (mask & (1 << j)):
sx, sy = stations[j]
nxt = mask | (1 << j)
cand = dp[mask] + abs(wx - sx) + abs(wy - sy)
if cand < dp[nxt]:
dp[nxt] = cand
best = inf
for mask in range(1 << m):
if bin(mask).count("1") == n and dp[mask] < best:
best = dp[mask]
return best