Editorial for COI '10 #1 Sort
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.
Submitting an official solution before solving the problem yourself is a bannable offence.
The most important observation is that there exists a solution in which at most two cyclic swaps are needed. We can divide the solution into a few separate cases:
- Starting array is sorted – in this case, there is no need for any swap.
- One swap is enough – If there is number
at the position
in starting array and in position
there is number
, at position
number
, …, at position
there is number
, then this configuration is called interesting. For example, starting array
is one big interesting configuration. In this case, only one swap is necessary.
- Two swaps are enough – it is easy to show that starting array can be partitioned into a finite number of interesting configurations (or subsets). If we make a cyclic swap with one number from every interesting subset, they all will combine into one big interesting configuration for which is then only one swap needed.
Comments