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 ai and the i-th girl initially has a location of bi. We define the distance between the i-th guy and the j-th girl to be |aibj|. 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 ui-th guy and the vi-th girl swap locations. Initially and after each of Q minutes, help Alice compute the minimum inconvenience factor over all perfect matchings.

Constraints

1N105

0Q2×105

1ai,bi109

1ui,viN

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 a1,,aN.

The third line contains N integers b1,,bN.

The next Q lines each contain 2 integers ui and vi.

Output Specification

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

Sample Input

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

Sample Output

Copy
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 |23|+|45|+|16|=7.

After the first swap, the best matching is given by {(1,3),(2,2),(3,1)}. This matching has an inconvenience factor of |21|+|43|+|65|=3.

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

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


Comments

There are no comments at the moment.