## Editorial for DMOPC '22 Contest 1 P2 - Hat Swap

**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.**

Author:

Notice this problem can be visualized by viewing the action of "swapping" as travelling along an edge on a graph with node as Shirogane and node as Kaguya.

##### Subtask 1

For the first , we loop through each hat color from to and calculate the cost to swap both Kaguya and Shirogane's hat to color .

We can simulate this process by first letting Shirogane swap to the closest person with color . And then let Kaguya swap to the closest person to him with color that hasn't been swapped with Shirogane already. Notice this might not produce the best answer for color , and we also have to do it but with Kaguya going first and Shirogane going second. Then we can take the minimum of the two results to get the minimum cost for color .

For each case, we can run breadth-first search once for each person to find the closest hat still available to that person, resulting in a time complexity of .

##### Subtask 2

To get full score, we have to optimize the process of searching for the best answer for each hat color. Notice that there are two main cases of an optimal answer for some hat color :

- The closest hat of color from node (Shirogane) and (Kaguya) are different. In this case they both take the closest hat to them.
- The closest hat of color from both of them are the same. In this case we have to let a person take their second closest choice.

So we have to keep track of the closest and second closest node of each hat color for both Shirogane and Kaguya, which can be done by running breadth-first search once from node and once from node . Then we can calculate the optimal answer for each hat color in by considering the aforementioned two cases, resulting in a time complexity of .

## Comments