All problems

Problem 654

Count Different Palindromic Subsequences

Hard · 30 pts · String, Dynamic Programming

Problem

Count the different non-empty palindromic subsequences of a string S made of the letters a, b, c and d. Two subsequences are the same if they are the same string, no matter which positions they come from. Print the count modulo 1000000007. Let count(i, j) be the answer for S[i..j]. If S[i] = S[j], look at the next and previous occurrences of that letter inside the range: no inner copy, one, or several give 2c + 2, 2c + 1, or 2c - count(inner range), where c = count(i + 1, j - 1). Keep the counts in a 64-bit integer type (long long in C++, long in Java) and take the remainder after every addition and multiplication: adding or multiplying two remainders can be larger than a 32-bit int can hold (Python needs nothing special).

Input

A single string S of the letters a, b, c and d.

Output

Print the number of different palindromic subsequences modulo 1000000007.

Constraints

1 <= |S| <= 1000

Example input

bccb

Example output

6

Explanation

The string bccb has the palindromic subsequences b, c, bb, cc, bcb and bccb. Each is counted once even though some appear at several positions, so the answer is 6.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Minimum Number of Refueling Stops Next: Strange Printer