题目2 : 回文字符序列
时间限制:
2000ms
单点时限:
1000ms
内存限制:
256MB
-
5 aba abcbaddabcba 12111112351121 ccccccc fdadfa
样例输出
-
Case #1: 5 Case #2: 277 Case #3: 1333 Case #4: 127 Case #5: 17
#include <iostream> #include<stdio.h> #include<string.h> #include<algorithm> #include<map> using namespace std; char s[1010]; int num[1010]; int dp[1010][1010]; int main() { int T,t; cin>>T; t=1; while(T--) { scanf("%s",s); int len=strlen(s); map<char,int> m; for(int i=0;i<len;i++) { if(m.find(s[i])==m.end()) { m[s[i]]=i; num[i]=-1; } else { num[i]=m[s[i]]; m[s[i]]=i; } } memset(dp,0,sizeof(dp)); for(int i=0;i<len;i++) for(int j=i;j>=0;j--) { if(i==j) { dp[i][j]=1; continue; } int e=i; while(num[e]>=j) { if(i-1>num[e]+1) { dp[j][i]+=dp[num[e]+1][i-1]+1; e=num[e]; } else if(i-1==num[e]+1) { dp[j][i]+=2; e=num[e]; } else { dp[j][i]+=1; e=num[e]; } } dp[j][i]+=dp[j][i-1]+1; } printf("Case #%d: ",t++); printf("%d\n",dp[0][len-1]); } }
描述
给定字符串,求它的回文子序列个数。回文子序列反转字符顺序后仍然与原序列相同。例如字符串aba中,回文子序列为"a", "a", "aa", "b", "aba",共5个。内容相同位置不同的子序列算不同的子序列。
输入
第一行一个整数T,表示数据组数。之后是T组数据,每组数据为一行字符串。
输出
对于每组数据输出一行,格式为"Case #X: Y",X代表数据编号(从1开始),Y为答案。答案对100007取模。
数据范围
1 ≤ T ≤ 30
小数据
字符串长度 ≤ 25
大数据
字符串长度 ≤ 1000