HDU 4632 回文串(区间dp)
Palindrome subsequence
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 is a subsequence of .
(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 = and Y = , 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
分析:区间dp问题,状态方程:dp(i,j)=(dp(i+1,j)+dp(i,j-1)-dp(i+1,j-1)+mod)%mod,因为()内可能小于0,故加上mod。表示从I到j的回文串个数
if(s[i]==s[j]),则 还有加上1+dp(i+1,j-1);
AC代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=1000+10;
const int mod=10007;
char s[maxn];
int dp[maxn][maxn];
int main(){
int T;
scanf("%d",&T);
int count1=0;
while(T--){
scanf("%s",s+1);
int l=strlen(s+1);
memset(dp,0,sizeof(dp));
for(int len=1;len<=l;len++) //长度
for(int i=1;i<=l-len+1;i++){ //起点位置
int j=i+len-1; //终点位置
dp[i][j]=(dp[i][j-1]+dp[i+1][j]-dp[i+1][j-1] + mod)%mod;
if(s[i]==s[j])
dp[i][j]=(dp[i][j]+1+dp[i+1][j-1])%mod; //首尾是一个回文串,并且中间任何一个回文串和首尾组成的仍是一个回文串
}
printf("Case %d: ",++count1);
printf("%d\n",dp[1][l]);
}
return 0;
}
还没有评论,来说两句吧...