Editorial for DMPG '19 S5 - Secret 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.

Author: r3mark

Consider the array a1,a2,,aN and consider two indices i,j with i<j. Let x be the number of elements in the subarray from i to j with value between ai and aj exclusive. Consider how the number of inversions changes if the elements with indices i and j are swapped. It turns out that if ai<aj, then the number of inversions increases by 1+2u and if ai>aj, then the number decreases by 1+2u. So u can be determined by swapping i and j.

Observe that if i=1 and j=N, then the subarray from 1 to N contains every number from 1 to N. So the value u+1 is simply the difference between ai and aj. We will extend this idea. First, set i=1,j=N. This tells us aN relative to a1. Next, set i=1,j=N1. Though the subarray from 1 to N1 is no longer every number, we know the value of aN relative to a1 and aN is the only missing number. So we can determine aN1 relative to a1. We continue this with j=N2,N3,,2 to determine every element of the array relative to each other. Using this, each element can be identified. This took N1 swaps (plus another at the start to get the initial number of inversions). Once the elements are known, it is easy to sort the array in N1 swaps. This totals to 2N1 which is just barely under the limit.

Time Complexity: O(N2)


Comments

There are no comments at the moment.