Palindrome subsequence

来源:互联网 发布:淘宝开店零食起名字 编辑:程序博客网 时间:2024/05/21 14:08

                                          F - Palindrome subsequence

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 = <Sx1, 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.


一个比较神奇的题,题意是要在一字符串里按顺序取出一些字符,使其成为回文子序列,求出最多能组成多少种不同的回文子序列,需要用到区间dp,dp[i][j]表示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<cstdio>#include<cstring>#define mod 10007using namespace std;int dp[1010][1010];int main(){    int t;    scanf("%d",&t);    for(int k=1;k<=t;k++)    {        memset(dp,0,sizeof(dp));        char a[1010];        cin>>a;        int len=strlen(a);        for(int i=0;i<len;i++)            dp[i][i]=1;        for(int j=1;j<len;j++)                                                         for(int i=j-1;i>=0;i--)                                                 {            dp[i][j]=(dp[i+1][j]+dp[i][j-1]-dp[i+1][j-1]+mod)%mod;          //对于有“-”号的式子,有可能会出现负数,所以需要加上一个mod来确保为正数再取余                                        if(a[i]==a[j])                dp[i][j]=(dp[i][j]+dp[i+1][j-1]+1+mod)%mod;                                        //相等时还要加上dp[i+1][j-1]+1.        printf("Case %d: %d\n",k,dp[0][len-1]);    }    return 0;}

0 0
原创粉丝点击