Editorial for COCI '23 Contest 5 #3 Piratski Kod


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.

For 20 points it was enough to carefully implement a brute force algorithm calculating values of all pirate codes.

Let's introduce some notation:

  • C(k) - number of pirate entries of length k.
  • S(k) - sum of values of all pirate entries of length k.
  • f(n) - sum of values of all pirate codes of length n.

We can easily notice that f(n) = \sum_{k=1}^n C(k) \times f(n-k) + 2^{n-k} \times S(k). It only remains to determine C(k) and S(k).

Number of pirate entries of length k is C(k) = Fib[k-1] because we see that from a pirate entry of length k-2, by changing the last digit to 0 and concatenating two ones at the end we get a pirate entry of length k that ends with 1011. From a pirate entry of length k-1, by changing second to last digit to 0 and concatenating a single 1 at the end, we get a pirate entry of length k that ends with 0011. From this analysis we get a recursion of Fibonacci numbers and we can easily check the basis for k = 1, 2.

Pirate entries of length k represent numbers from Fib[k] to Fib[k+1]-1 so the following holds:

\displaystyle S(k) = \frac{Fib[k+1](Fib[k+1]-1)-Fib[k](Fib[k]+1)}{2}.

Now we can finish the task with dynamic programming in time complexity \mathcal{O}(n^2).


Comments

There are no comments at the moment.