Editorial for IOI '05 P4 - Birthday
Submitting an official solution before solving the problem yourself is a bannable offence.
The task is to find such an arrangement of the children, that the maximum number of seats any child has to be moved is minimized. At first we should note, that there are two classes of possible final arrangements. For example, if we have a permutation , then child can be either a left-hand-side or a right-hand-side neighbour of child . The first case will be called counterclockwise arrangement, the second will be called clockwise. In both cases calculations are similar, therefore we will only consider clockwise arrangements. Contestants have to consider both cases and choose the smaller result.
Simple solution
The first idea may be to perform simulations of all possible rearrangements. Let us fix the position of the first child. Now, using the given permutation, we can calculate the final positions (and also the distances of movements) of all the children in time complexity. Since we have to perform this step for all the possible positions of the first child, the total time complexity is .
Optimal solution
There exists a better solution. We denote by the given permutation of the children. Let us consider a final arrangement of the children, where the final position of child is . To achieve this arrangement, some (maybe all) of the children have to move. We can describe the movement of child by a number , where is the distance of movement, it is positive if the child moves clockwise, and negative if the child moves counterclockwise. Moreover, we assume, that the children always choose such a direction of movement, that the distance is smaller than in other direction (or choose clockwise if both distances are equal), that is .
Let . We can treat as an alternative representation of the considered rearrangement. Having this representation, we can easily calculate the maximum movement distance using formula:
Values of depend on the given permutation and . They can be characterized by the following formula:
Moreover, given some representation , we can easily compute by "shifting" all elements of (i.e. we replace by if and we replace by ).
Now we are interested in calculating the smallest possible result for all 's. Please note that all the representations are shifts of one base representation, say . Let us denote by the maximum number of consecutive (modulo ) elements from not appearing in . It can be calculated in linear time.
The result is equal to . This gives us an algorithm with time complexity.
Comments