In mathematics, a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, the sequence <A, B, D> is a subsequence of <A, B, C, D, E, F>. (http://en.wikipedia.org/wiki/Subsequence) Given a string S, your task is to find out how many different subsequence of S is palindrome. Note that for any two subsequence X = <S x1, S x2, ..., S xk> and Y = <S y1, S y2, ..., S yk> , if there exist an integer i (1<=i<=k) such that xi != yi, the subsequence X and Y should be consider different even if S xi = S yi. Also two subsequences with different length should be considered different.
InputThe first line contains only one integer T (T<=50), which is the number of test cases. Each test case contains a string S, the length of S is not greater than 1000 and only contains lowercase letters.OutputFor each test case, output the case number first, then output the number of different subsequence of the given string, the answer should be module 10007.Sample Input
4aaaaaagoodafternooneveryonewelcometoooxxourproblems
Sample Output
Case 1: 1Case 2: 31Case 3: 421Case 4: 960
大致题意是给定一个字符串,求回文子序列个数,最后的答案要%10007
首先定义f数组f[l][r]表示l~r区间的回文子序列个数,f[i][i]=1;
显然 根据容斥原理 :f[l][r]=f[l][r-1]+f[l+1][r]-f[l+1][r-1] (因为中间的个数会算两遍);
然后,我们考虑s[l]==s[r]的情况,如果这两个位置相等,那么l+1 ~ r-1这个区间的所有子序列,都可以加入l和r这两个元素,构成一个新的回文子序列,除此之外 l和r这两个元素也可以构成一个回文子序列
注意减的时候取模+要加模
代码:
#include#include #include #include #include #include #include #include #include