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
and consider two indices
with
. Let
be the number of elements in the subarray from
to
with value between
and
exclusive. Consider how the number of inversions changes if the elements with indices
and
are swapped. It turns out that if
, then the number of inversions increases by
and if
, then the number decreases by
. So
can be determined by swapping
and
.
Observe that if
and
, then the subarray from
to
contains every number from
to
. So the value
is simply the difference between
and
. We will extend this idea. First, set
. This tells us
relative to
. Next, set
. Though the subarray from
to
is no longer every number, we know the value of
relative to
and
is the only missing number. So we can determine
relative to
. We continue this with
to determine every element of the array relative to each other. Using this, each element can be identified. This took
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
swaps. This totals to
which is just barely under the limit.
Time Complexity: 
Comments