Problem 2: Batmanacci
https://open.kattis.com/problems/batmanacci
Given N and K, find the Kth letter in the Nth Batmanacci string.
We can store the length of each Batmanacci string in a list. (The length of theNthstring is simply the NthFibonacci number.)
Recurrence relation for the lengths:
Length[i] = Length[i - 1] + Length[i - 2], with base cases Length[0] = 0 and Length[1] = 1.
We can build the list of lengths using DP.
Observe that given someNth string, the first part of this string is the (N−2)th string.
If K is within the length of that (N−2)th string, then we can check that (N−2)th string to find the answer. (Denote the length of this (N−2)th string as L.)
Otherwise,K is greater than the length of the (N−2)thstring. Then the answer corresponds to the (K−L)th letter in the(N−1)thstring.
We can recursively obtain the desired Kth letter in the Nth string, taking advantage of the word lengths we previously stored.
Base cases in the recursion:
N = 1: answer is 'N'N = 2: answer is 'A'
Recurrence relation:
If
K <= Length[N-2], go to the case forN-2, K.Otherwise,
K > Length[N-2], so we go to the case forN-1, K-L.
After these recursive calls, we will arrive at one of the base cases (which gives us the final answer).
Note: make sure to use unsigned long long because the numbers can get very large.
For largeN, Length[N]may cause overflow. Thus, if Length[N]>1018 , we can just set it to1018since that's the maximum input value forK.
Last updated