Problem author: | Maryan Shyika |
Prepared by: | Maryan Shyika |
Tutorial: | Maryan Shyika |
Idea
The final score of a person is equal to the maximum value a_j among all positions they visit during days.
First, let us check whether a solution can exist. If for at least one person starting at position we have
then already on the first day their score becomes greater than the required value . In this case, the answer is .
Now group people by their value . For each such group, divide the people into two types:
Good — people for whom a_s=c. Such a position already provides the required maximum.
Bad — people for whom a_s<c. In order for their final score to become equal to , they have to visit a position with value a_i=c.
Consider one group with the same value . We use every position from Good as an anchor of a separate cycle. We can add at most x-1 positions from Bad to this cycle.
Thus, the length of every such cycle does not exceed , so every person in it will visit the anchor with value during days. At the same time, all other positions containing people in this cycle have values not greater than , so the final maximum will be exactly .
If some elements from Bad remain after using all positions from Good, we need to create additional cycles for them. As an anchor for such a cycle, we use a free position without a person for which
Again, we add at most x-1 positions from Bad to each such anchor.
If there are not enough free positions with value , it is impossible to construct a valid permutation, so we output .
Also, if x=1 and there is at least one position from Bad, the answer is immediately , since such a person cannot reach another position.
After processing all groups, every constructed set of positions
is closed into a cycle:
All positions that were not used in any cycle are made fixed points:
Thus, we obtain a valid permutation for which the final score of every person is equal to the required value .
The overall time complexity is O(n\log n) due to the use of std::map.
The memory complexity is .