KatInterview

Pair Workers With Distinct Stations at Minimum Grid Distance

Dynamic ProgrammingAuto-graded · 25 test cases
MediumAuto-gradedDynamic Programmingbitmask-dpassignment-problemmanhattan-distance

Last 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 of n pairs [x, y], the worker positions.
  • stations: a list of m pairs [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 <= 10
  • n <= 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.