Editorial for Perfect Pairing
Remember to use this editorial only when stuck, and not to 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.
Submitting an official solution before solving the problem yourself is a bannable offence.
Approach
Let the sorted versions of the arrays be
and
.
Consider any matching after both arrays are sorted. If there are two pairs that cross, say
is matched with
and
is matched with
, where
but
,
then swapping those two pairs cannot increase the total cost.
Intuitively, crossing lines are wasteful: the smaller value from should not skip past the
smaller value from
while the larger value from
goes backward. Repeatedly uncrossing
pairs produces an optimal matching with no crossings, and the only non-crossing perfect matching
is
.
So the algorithm is:
- Sort both arrays.
- Pair them in order.
- Sum
.
This runs in 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)
Comments