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
4
a
aaaaa
goodafternooneveryone
welcometoooxxourproblemsSample Output
Case 1: 1
Case 2: 31
Case 3: 421
Case 4: 960
分析:
区间dp变化很多,我这种萌新还是too young too simple~
本题的意思是:
求回区间不连续文子串的个数,而不是求长度
dp[i][j]=dp[i+1][j]+dp[i][j-1]-dp[i+1][j-1]//dp[i+1][j-1]加了两遍所以要减去一遍
如果s[i]==s[j]则dp[i][j]+=dp[i+1][j-1]+1
原因:若s[i]==s[j],则在dp[i][j]=dp[i+1][j]+dp[i][j-1]-dp[i+1][j-1]的基础上,s[i]加上区间[i,j]任意一个回文子串(一共有dp[i+1][j-1]个),与s[j]都能构成回文子串,加1是s[i],s[j]构成的回文子串。
eg.
3 1 1 3
dp[1][4]=dp[2][4]+dp[1][3]-dp[2][3]=4+4-3=7
又因为s[1]==s[4],所以dp[1][4]+=dp[2][3]+1
加上的dp[2][3]的数值代表着:
3 1 3
3 1 3
3 11 3 (红色表示dp[2][3]的回文串)
1代表 3 3
代码如下:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
char s[1003];
int dp[1003][1003];
int main(){
int n;
scanf("%d",&n);
for(int q=1;q<=n;q++){
scanf("%s",s+1);
int len=strlen(s+1);
memset(dp,0,sizeof(dp));
for(int i=1;i<=len;i++)dp[i][i]=1;
for(int r=2;r<=len;r++){
for(int i=1;i<=len-r+1;i++){
int j=i+r-1;//长度为r的区间的终点
dp[i][j]=(dp[i+1][j]+dp[i][j-1]-dp[i+1][j-1]+10007)007;
if(s[i]==s[j])dp[i][j]=(dp[i][j]+dp[i+1][j-1]+1)007;
}
}
printf("Case %d: %d\n",q,dp[1][len]);
}
}