Editorial for Perfect Pairing


Approach

Let the sorted versions of the arrays be a1≤a2≤⋯≤ana_1 \le a_2 \le \dots \le a_n and b1≤b2≤⋯≤bnb_1 \le b_2 \le \dots \le b_n.

Consider any matching after both arrays are sorted. If there are two pairs that cross, say aia_i is matched with bqb_q and aja_j is matched with bpb_p, where i<ji < j but p<qp < q, then swapping those two pairs cannot increase the total cost.

Intuitively, crossing lines are wasteful: the smaller value from aa should not skip past the smaller value from bb while the larger value from aa goes backward. Repeatedly uncrossing pairs produces an optimal matching with no crossings, and the only non-crossing perfect matching is (a1,b1),(a2,b2),…,(an,bn)(a_1, b_1), (a_2, b_2), \dots, (a_n, b_n).

So the algorithm is:

  1. Sort both arrays.
  2. Pair them in order.
  3. Sum ∣ai−bi∣|a_i - b_i|.

This runs in O(nlog⁡n)O(n \log n) because of sorting.

Solution (Python)

Code 1
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))

a.sort()
b.sort()

answer = 0
for x, y in zip(a, b):
    answer += abs(x - y)

print(answer)

Comments0


No comments yet

Be the first to comment.

New comment


Log in to join the discussion.