Editorial for Perfect Pairing
Use this editorial only when stuck, and do not copy-paste code from it.
Please be respectful to the problem author and editorialist. Submitting an official solution before solving the problem yourself is a bannable offence.
Approach
Let the sorted versions of the arrays be a1≤a2≤⋯≤an and b1≤b2≤⋯≤bn.
Consider any matching after both arrays are sorted. If there are two pairs that cross, say ai is matched with bq and aj is matched with bp, where i<j but p<q, then swapping those two pairs cannot increase the total cost.
Intuitively, crossing lines are wasteful: the smaller value from a should not skip past the smaller value from b while the larger value from a 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).
So the algorithm is:
- Sort both arrays.
- Pair them in order.
- Sum ∣ai−bi∣.
This runs in O(nlogn) because of sorting.
Solution (Python)
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.