F: Base-2 Palindromes

https://open.kattis.com/problems/base2palindrome

  • The key observation in this problem is that a palindrome is uniquely defined by the first half bits. Thus, the number of palindromes of length nn (n>=2n>=2) with the first bit 11 is 2n222^{\lceil\frac{n-2}{2}\rceil}.

  • We can figure out the most significant bit of the mthm^{th} palindrome by counting the number of palindromes of each length until the total number of palindromes we have counted so far exceeds mm.

  • Suppose the most significant bit of the mthm^{th} palindrome is the bthb^{th} bit, and suppose there are kk palindromes of length at most b1b-1. Then, we are interested in the m=(mk)thm' = (m-k)^{th}​palindrome of length bb .

  • Let ss denote the binary representation of mk1m-k-1. Let srevs_{rev} denote the string ss reversed. Now, we know that the answer is 1ssrev11ss_{rev}1 (expect if bb is odd, in which case we remove one bit from srevs_{rev}​).

    • For instance, suppose s=0101s=0101. If bb is even, the answer is 10101101011010110101. If b is odd, the answer is 101010101101010101.

  • Finally, convert the binary string to an integer.

Last updated