Comments

When we say that the number of inversions involving $$$i$$$ depends only on $$$a_i$$$, we mean that it doesn’t matter what decisions we make for the other elements: if an element is greater than $$$p_i$$$, it will remain greater regardless of whether we keep it as $$$p_j$$$ or change it to $$$2n - p_j$$$; and if it is smaller, it will remain smaller in both cases.

The key is to count the inversions involving $$$i$$$ without double-counting cases.

If we set $$$a_i = p_i$$$ (small value), then all elements greater than $$$p_i$$$ that are to the left will form inversions with $$$i$$$. This remains true even if those elements are changed to $$$2n - p_j$$$, because they will still be greater than $$$p_i$$$.

If we set $$$a_i = 2n - p_i$$$ (large value), then all elements greater than $$$p_i$$$ that are to the right will form inversions with $$$i$$$. This also remains true even if they are changed to their large form, because they will still be smaller than $$$a_i$$$.

Thus, for each $$$i$$$, there are only two possible inversion counts involving it:

$$$ \min(\#\ \text{greater to the left},\ \#\ \text{greater to the right}) $$$

We choose the smaller of the two, then remove $$$i$$$ from the array. After this, the remaining problem is of exactly the same type, so the process repeats recursively until all positions are processed.

I hope to improve my rating now, I had a bad streak.