(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.
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代码:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <vector>
using namespace std;
const int MAXN = 1005;
char S[MAXN];
int dp[MAXN][MAXN];
int main()
{
int T;
scanf("%d",&T);
for(int I=1 ; I<=T ; I++)
{
scanf("%s",S);
int len = strlen(S);
memset(dp,0,sizeof(dp));
for(int i=0 ; i<len ; i++)
{
dp[i][i] = 1;
}
for(int l=1 ; l<len ; l++)
{
for(int i=0 ; i<len-l ; i++)
{
dp[i][i+l] = (dp[i][i+l-1]+dp[i+1][i+l]-dp[i+1][i+l-1]+10007)%10007;//这里注意相减可能会出现负数
if(S[i] == S[i+l])//注意当S[i]==S[i+l]时S[i+1]到S[i+l-1]范围内的回文序列都可以与这两个字符拼接成一个新的。
{
dp[i][i+l] = (dp[i][i+l]+dp[i+1][i+l-1]+1)%10007;//+1是S[i]和S[i+l]两个字符拼接的情况。
}
}
}
printf("Case %d: %d\n",I,dp[0][len-1]);
}
return 0;
}