Editorial
Let and . The minimum allowed interval length is .
1. Swapping two distant positions
Suppose and . Reverse the following two intervals in order.
The first reversal exchanges the two endpoints and reverses the interior. The second reversal restores only the interior. Therefore, only the elements at positions and are exchanged.
The second interval has length , so both reversals are allowed. When and the two positions are adjacent, reversing only is sufficient.
2. A coordinate system with one fixed endpoint
First use position as the endpoint. Let be the reversal of . It fixes position and maps every other position to .
The two distances
sum to . Therefore, at least one of them is at least . If is too close to position in the current coordinate system, applying once makes it sufficiently far away.
Treat the state after applying as another coordinate system. Only the actual position representing each logical position changes. Swapping two actual positions in that coordinate system swaps the corresponding logical positions. One Boolean value is enough to remember whether this coordinate system is reversed.
The construction for endpoint is symmetric and uses the reversal .
3. A cycle containing the endpoint
Consider a permutation cycle
where and . Suppose is the current endpoint.
Swap the following pairs of logical positions in order:
These swaps fix every position in the cycle.
Before each swap, if the other position is too close to the endpoint, apply the auxiliary reversal once. The two positions can then be exchanged with two reversals. The swaps require reversals. Coordinate-system changes are needed at most once before each swap and at most once more at the end, for at most changes.
Thus, a cycle of length containing the endpoint can be processed using at most
reversals.
4. A cycle not containing an endpoint
Choose an initial position of the cycle.
If , reverse . This reversal is allowed and maps logical position to actual position .
If , reverse . This reversal is also allowed and maps logical position to actual position .
Process the cycle in this coordinate system using the previous construction, and then reverse the initial interval again to restore the original coordinate system. The first and last reversals add two operations, so a cycle of length needs at most
reversals.
5. Total number of operations and implementation
Cycles of length require no operation. Process every other cycle independently. The sum of their lengths is at most , so the total number of reversals is at most .
In the implementation, compute the cycle decomposition of the permutation. For each cycle, maintain the selected endpoint, the initial coordinate transformation, and one Boolean value for the auxiliary reversal. There is no need to simulate the entire array.
The time complexity excluding the printed output is , and the number of printed operations is .
Solution written by GPT5.6