Official

F - Shift and Inversions Editorial by en_translator


The inversion number can be calculated in an \(O(N \log N)\) with a method like Fenwick Tree.
However, if this is done for every \(B\), it will cost \(O(N^2 \log N)\) time, which will lead to TLE.

Observe that, when \(k = i\) is changed to \(k = i + 1\), \(B\) does not change so much; how the inversion number changes then?

Changing \(k = i\) to \(k = i + 1\) is equivalent to:

  • removing \(a_i\), the first element of \(B\), and then
  • adding \(a_i\) as the last element of \(B\).

When \(a_i\) is removed from the first element of \(B\), the inversion number decreases by \(a_i\), and when \(a_i\) is added as the last element, the inversion number increases by \(N - 1 - a_i\).
Therefore, when \(k = i\) is changed to \(k = i + 1\), the inversion number is changed by \(N - 1 - 2 \times a_i\).

Since the delta of the inversion numbers can be found in an \(O(1)\) time, the problem can be solved in a total of \(O(N \log N)\) time, where the process of finding the inversion number of \(A\) is the bottleneck.

Sample Code (C++) : https://atcoder.jp/contests/abc190/submissions/19761416
Sample Code (Python) : https://atcoder.jp/contests/abc190/submissions/19761422

posted:
last update: