Editorial for DMOPC '19 Contest 7 P5 - Soriya's Programming Project


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: Kirito

The first subtask is very similar to the classic inversion counting problem.

For every i, the number of new inversions is equal to the number of j<i where aj<ai. This can be found in O(NlogN) time by using a range tree.

Time Complexity: O(NlogN)

For the second subtask, we can maintain a range tree to count the number of 1's in a given range, and a second range tree to count the number of 2's in a given range.

If api=1, then the number of new inversions is the number of j<pi such that aj=2. If api=2, then the number of new inversions is the number of j>pi such that aj=1.

Time Complexity: O(NlogN)

For the final subtask, we note that we can represent every value with the tuple (pi,ai,i).

One solution is to sort all of the points by their pi values. The number of new inversions equals the number of points where pj<pi, and either ai<ajj<i or ai>ajj>i.

A memory-optimized 2D data structure can solve this in O(Nlog2N).

Alternatively, we can use divide and conquer with a 1D range tree, which also yields an O(Nlog2N) solution.

Time Complexity: O(Nlog2N)


Comments

There are no comments at the moment.