hdu 4632 Palindrome subsequence

Posted 给杰瑞一块奶酪~

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hdu 4632 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 = <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
welcometoooxxourproblems
Sample Output
Case 1: 1
Case 2: 31
Case 3: 421
Case 4: 960
这里的子串不需要连续,区间dp,首先每个字符都是长度为1的回文串,然后确定长度为i的连续子串里有多少回文串(i>=2),这样长度为i的子串可以由它的长度为i-1的子串来更新。
代码:
#include <iostream>
#include <cstring>
#include <cstdio>
#define Max 1002
using namespace std;
int t,dp[Max][Max];
char s[Max];

int main()
{
    scanf("%d",&t);
    int k = 1;
    for(int i = 1;i <= 1001;i ++)
        dp[i][i] = 1;///从i到i长度为1的一个字符是长度为1的
    while(t --)
    {
        scanf("%s",s);
        int len = strlen(s);
        for(int i = 1;i <= len - 1;i ++)
        {
            for(int j = 1;j + i <= len;j ++)///j表示从i开始的子串长度
            {
                dp[j][i + j] = dp[j + 1][i + j] + dp[j][i + j - 1] - dp[j + 1][i + j - 1];///[a,b]区间的用[a+1,b] 和 [a,b-1]区间的更新,这两个区间肯定会较早就确定 但是他们都包含了[a+1,b-1]
                if(s[j - 1] == s[i + j - 1])dp[j][i + j] += dp[j + 1][i + j - 1] + 1;///如果边界两个字符相同那么这两个字符可以组成一个回文串 同时 区间内的回文串加上这两个字符又形成新的回文串
                dp[j][i + j] = (dp[j][i + j] + 10007) % 10007;
            }
        }
        printf("Case %d: %d\n",k ++,dp[1][len]);
    }
}

 

以上是关于hdu 4632 Palindrome subsequence的主要内容,如果未能解决你的问题,请参考以下文章

hdu-4632 Palindrome subsequence (回文子序列计数)

hdu4632 Palindrome subsequence 回文子序列个数 区间dp

HDU 4632 Palindrome subsequence(区间DP求回文子序列数)

HDU 4632 Palindrome subsequence (区间DP)

Palindrome subsequence (区间DP)

hdu4632 回文子序列