DMOPC '23 Contest 1 P5 - Perfect Matching

View as PDF

Submit solution

Points: 25 (partial)
Time limit: 3.0s
Memory limit: 1G

Author:
Problem types

Alice is developing a new online dating app, DMOPC (DMOJ Modern Online Pairing Client). The app currently has 2N users, N guys and N girls, where i-th guy initially has a location of a_i and the i-th girl initially has a location of b_i. We define the distance between the i-th guy and the j-th girl to be |a_i - b_j|. Instead of allowing the users to browse through potential candidates, DMOPC overcomes this choice overload by matching every guy with exactly one girl and vice versa (such a matching is deemed a perfect matching). Furthermore, according to Alice's utilitarian ideals, Alice believes that the best matching does not need to account for the personalities of each user, but is rather one where the sum of the distances between the people in each matched pair — the inconvenience factor — is minimized.

Of course, the users of DMOPC are constantly on the move. At the i-th minute, the u_i-th guy and the v_i-th girl swap locations. Initially and after each of Q minutes, help Alice compute the minimum inconvenience factor over all perfect matchings.

Constraints

1 \le N \le 10^5

0 \le Q \le 2 \times 10^5

1 \le a_i, b_i \le 10^9

1 \le u_i, v_i \le N

All 2N locations are pairwise distinct.

Subtask 1 [20%]

Q = 0

Subtask 2 [80%]

No additional constraints.

Input Specification

The first line contains 2 integers N and Q.

The second line contains N integers a_1, \dots, a_N.

The third line contains N integers b_1, \dots, b_N.

The next Q lines each contain 2 integers u_i and v_i.

Output Specification

Output Q+1 lines, the initial answer followed by the answers after each swap.

Sample Input

3 3
2 4 1
5 3 6
3 3
2 3
1 1

Sample Output

7
3
5
5

Explanation for Sample

Initially, the best matching is given by \{(1, 2), (2, 1), (3, 3)\}, where each pair (i, j) represents matching the i-th guy with the j-th girl. This matching has an inconvenience factor of |2 - 3| + |4 - 5| + |1 - 6| = 7.

After the first swap, the best matching is given by \{(1, 3), (2, 2), (3, 1)\}. This matching has an inconvenience factor of |2 - 1| + |4 - 3| + |6 - 5| = 3.

After the second swap, the best matching is given by \{(1, 2), (2, 3), (3, 1)\}. This matching has an inconvenience factor of |2 - 3| + |1 - 4| + |6 - 5| = 5.

After the third swap, the best matching is given by \{(1, 3), (2, 1), (3, 2)\}. This matching has an inconvenience factor of |5 - 4| + |1 - 2| + |6 - 3| = 5.


Comments

There are no comments at the moment.