Editorial for COCI '16 Contest 1 #5 Kralj


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.

In the description of this solution, all labels are considered cyclical, which means that label n+1 is actually 1, n+2 is actually 2, and so on.

For any order of sending the elves, a position k exists such that none of the elves have taken a walk from the k^\text{th} to the (k+1)^\text{th} dwarf, because the k^\text{th} dwarf was busy. This is pretty obvious, because this holds for the dwarf that got its opponent last. However, a much stronger claim also holds: there always exists at least one position k such that for each order of sending the elves, none of them has taken a walk between the k^\text{th} and the (k+1)^\text{th}. Let's define R_i as the number of dwarves whose assigned opponent has a label less than or equal to i, and let P_i = R_i-i. Notice that it must hold P_n = 0.

Let's take the smallest number out of all P_i, and say that it is obtained for position m. We will show that it is impossible for an elf to take a walk from position m to position m+1. Let's assume the contrary. This means that a sequence of positions exists a, a+1, \dots, m where it holds that the number of elves whose opponent is located on some of these positions is larger than the number of these positions. However, it holds that the difference between the number of elves whose opponent is located at one of these positions and the number of these positions is precisely equal to P_m-P_a. This holds, regardless of whether a is smaller or greater than m because P_n = 0. This difference cannot be positive, because of the selection of position m.

Now we can "cut through" the circle. In other words, observe it as an array of length n that starts at position m+1. Now we can solve the task using a greedy algorithm. Traversing from the beginning to the end of the array, we will push the strength of an elf into a set when we reach the position of its assigned opponent. We will select a dwarf's opponent the weakest elf from the set that can beat him, and if such doesn't exist, the weakest elf in the set. We will then remove the elf we selected from the set. The order of removal of elves from the set is the order in which they will enter the hall.

For solving the subtask worth 40\% of points, it was sufficient to implement a greedy algorithm with the beginning of the array in the first position, but it was possible to solve it using binary search.


Comments

There are no comments at the moment.