ksun48's blog

By ksun48, 11 years ago, In English

351E - Jeff and Permutation

Here is an alternate, simpler, solution to the one given in the editorial.

First, let's consider pi and pj in positions i < j. Let's first assume that |pi| ≠ |pj|. When will this be an inversion?

If |pi| > |pj|, then it is an inversion when pi is negative, and not when pi is positive, because  - |pi| <  - |pj| ≤ |pj| < |pi|. Thus our choice of pj does not affect if (i, j) is an inversion.

Similarly, if |pi| < |pj|, then the choice of pi does not matter.

Thus for each element pk, we can choose its sign by looking at the count of the |pi| < |pk|, with i < k and i > k. If there are more with i < k, we make pi positive, and otherwise, we make pi negative.

But wait! What if |pi| = |pj|? Then whether or not (i, j) is an inversion depends on both values. Fortunately, this is not a problem, as if we do the above algorithm, if |pi| = |pj|, then the algorithm will make pi ≤ pj, so (i, j) will not be an inversion.

This is because there cannot be more elements with absolute value at most |pi| left of i than right of i, and at the same time less elements with absolute value at most |pi| left of j than right of j.

This algorithm can run in O(n2) time, and uses O(n) memory (with no DP at all, only greedy). With some sorting and a data structure, I believe we can improve this to time.

  • Vote: I like it
  • 0
  • Vote: I do not like it