Editorial for Cheerio Contest 3 P4 - Bit Flips


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

There are a number of clues which may provide intuition for the full solution, including:

  • When comparing integers, higher bit positions are more significant than lower bit positions.
  • If some element has a bit set at the highest bit position, then every element to its right must also have this highest bit set.

This motivates the following observation:

If the bit positions are labelled from 0 to B, where 0 represents the lowest bit position and B represents the highest bit position, then an array is sorted if and only if:

  • There is a (potentially empty) prefix of the elements which do not have the bit at position B set, and the remaining (potentially empty) suffix has the bit at position B set, and
  • Both the prefix and suffix are sorted themselves, when only considering the bit positions up to B-1.

We can now formulate a dynamic programming recurrence.

Define dp[L][R][B] as the minimum number of moves to sort the subarray indexed from L to R (inclusive), when we only consider the bits up to position B. If ones[L][R][B] is the number of elements in the subarray [L, R] with the bit at position B set, and zeroes[L][R][B] is the number of elements in the subarray [L, R] with the bit at position B unset, then

\displaystyle dp[L][R][B] = \min_{i=L-1}^R (dp[L][i][B-1] + dp[i+1][R][B-1] + ones[L][i][B] + zeroes[i+1][R][B])

Time complexity: \mathcal{O}(N^3 \log(\max(a_i)))


Comments

There are no comments at the moment.