G: Palindromic Naming
https://open.kattis.com/problems/palindromic
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 dp[i][j] denote the number of palindromic subsequences of the substring sisi+1...sj.
Note that the empty string is not considered a palindrome.
Firstly, dp[i][i]=1 for all positions i as any string of length 1 is a palindrome. Further, dp[i][i+1]=3 if si=si+1 as si, si+1, and sisi+1 are all palindromes. Otherwise, dp[i][i+1]=2 as only si and si+1are 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 si=sj, we cannot create any new palindromes using the characters at positions i and j. Thus, by inclusion-exclusion, dp[i][j]=dp[i][j−1]+dp[i+1][j]−dp[i+1][j−1].
If , si=sj, for every palindrome in si+1...sj−1, we can add siand sjto create a new palindrome sisi+1...sj−1sj. Furthermore, sisjis also a palindrome. So, we have dp[i+1][j−1]+1 new palindromes in addition to the ones we already had. So, in this case, dp[i][j]=dp[i][j−1]+dp[i+1][j]+1.
The required answer is dp[1][n].
Remember to perform all calculations modulo 1 000 000 007.
Last updated