Problem Description
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 = <Sx1, Sx2, ..., Sxk> and Y = <Sy1, Sy2, ..., Syk> , if there exist an integer i (1<=i<=k) such that xi != yi, the subsequence X and Y should be consider different even if Sxi = Syi. Also two subsequences with different length should be considered different.
Input
The 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.
Output
For 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
4
a
aaaaa
goodafternooneveryone
welcometoooxxourproblems
Sample Output
Case 1: 1
Case 2: 31
Case 3: 421
Case 4: 960
题意
给个字符串,问有多少子串是回文字符串。例如aba,先列出所有的个子串,在判断这些子串是不是回文,然后数是回文的个数。所以对于 a 和 a两个子串,因为是第一个a和第三个a,这俩算是不同的子串。
思路
对于dp[ i ] [ j ],字符串 i 到 j 区间,和前面的dp有两种情况的关系:
①如果s[ i ] != s[ j ]: dp[ i ] [ j ] = dp[ i+1 ] [ j ] + dp[ i ] [ j-1 ] - dp[ i+1 ] [ j-1 ],中间部分和左边的回文个数加上中间部分和右边的回文个数,会重复只有中间部分的回文个数。
②如果s[ i ] == s[ j ]: 仍然是第一种左边加右边减去中间,还有就是两边都有的情况,两边满足回文,中间也满足回文就行了,所以是dp[ i+1 ] [ j-1 ],还有只有s[ i ]和s[ j ],也是回文串,还有再加1。
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
const int mod = 10007;
int dp[1010][1010];
char str[1010];
int main()
{
int T; scanf("%d",&T);
for(int tt=1;tt<=T;tt++)
{
scanf("%s",str+1);
int len = strlen(str+1);
for(int i=1;i<=len;i++) dp[i][i] = 1;
for(int l=1;l<=len;l++){
for(int i=1;i<=len;i++){
int j = i+l-1;
if(j>len) continue;
dp[i][j] = (dp[i+1][j]+dp[i][j-1]-dp[i+1][j-1]+mod)%mod;
//dp[i+1][j-1],当i+1>j-1,dp为0,不影响
if(str[i]==str[j]) dp[i][j] = (dp[i][j]+dp[i+1][j-1]+1)%mod;
}
}
printf("Case %d: %d\n",tt,dp[1][len]);
}
return 0;
}