G: Palindromic Naming
https://open.kattis.com/problems/palindromic
Last updated
https://open.kattis.com/problems/palindromic
Last updated
Firstly, notice that the problem is essentially asking for the number of subsequences of the original string that are palindromes. As there are exponentially many subsequences, generating all possible subsequences and checking if it is a palindrome is too slow!
You can use dynamic programming to solve this problem :)
Let denote the number of palindromic subsequences of the substring .
Note that the empty string is not considered a palindrome.
Firstly, for all positions as any string of length is a palindrome. Further, if as , , and are all palindromes. Otherwise, as only and are palindromes.
We iterate in increasing order of widths w
. In other words, we first considering all palindromic subsequences at most 2 characters apart, then at most 3 characters apart and so on.
Now, our transitions:
If , we cannot create any new palindromes using the characters at positions and . Thus, by, .
If , , for every palindrome in , we can add and to create a new palindrome . Furthermore, is also a palindrome. So, we have new palindromes in addition to the ones we already had. So, in this case, .
The required answer is .
Remember to perform all calculations modulo 1 000 000 007.