回文串(dp题)

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.
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.

大概题意就是要在一字符串里按顺序取出一些字符,使其成为回文子序列,求出最多能组成多少种不同的回文子序列。还有一句重要的话就是he answer should be module 10007.
设dp[i][j]表示i到j区间内的字符串可以构成多少个不同的回文子序列。
一般情况:dp[i][j]=dp[i][j-1]+dp[i+1][j]-dp[i+1][j-1].也就是左右两个比他小1的区间之和再减去重复的部分。
特殊情况:当左右端点相等时,左右端点加上中间任意一个回文子序列都可以构成一个新的回文序列,而且左右端点还可以自己构成一个回文序列,所以当端点相等时还要加上dp[i+1][j-1]+1.

#include < iostream>
#include < algorithm>
#include < cstdio>
#include < cmath>
#include < cstring>
#include < string>
using namespace std;
typedef long long ll;
const int maxn=1010;
const int MOD=10007;
int dp[maxn][maxn];
int main()
{
int t,ans=1;
cin>>t;
while(t–)
{
string s;
cin>>s;
int len=s.size();
memset(dp,0,sizeof(dp));
for(int i=0;i<len;i++)
dp[i][i] = 1;
ll sum=0;
for(int i=1;i<=len;i++)
{
for(int j=0,k=j+i;k<len;j++,k++)
{
dp[j][k]=(dp[j][k-1]+dp[j+1][k]-dp[j+1][k-1]+MOD)%MOD;//对于有“-”号的式子,有可能会出现负数,所以需要加上一个mod来确保为正数再取余
if(s[j]==s[k])
dp[j][k]=(dp[j][k]+dp[j+1][k-1]+1+MOD)%MOD;
}
}
printf(“Case %d: %d\n”,ans++,dp[0][len-1]);
}
return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值