HDU4632-Palindrome subsequence(區間DP 迴文子序列)

題目鏈接

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 <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, Sx2, ..., Sxk> and Y = <Sy1, Sy2, ..., Syk> , if there exist an integer i (1<=i<=k) such that xi != yi, the subsequence X and Y should be consider different even if Sxi = Syi. 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


題意

給個字符串,問有多少子串是迴文字符串。例如aba,先列出所有的2^{n}-1個子串,在判斷這些子串是不是迴文,然後數是迴文的個數。所以對於 a 和 a兩個子串,因爲是第一個a和第三個a,這倆算是不同的子串。

思路

對於dp[ i ] [ j ],字符串 i 到 j 區間,和前面的dp有兩種情況的關係:

①如果s[ i ] != s[ j ]: dp[ i ] [ j ] = dp[ i+1 ] [ j ] + dp[ i ] [ j-1 ] - dp[ i+1 ] [ j-1 ],中間部分和左邊的迴文個數加上中間部分和右邊的迴文個數,會重複只有中間部分的迴文個數。

②如果s[ i ] == s[ j ]: 仍然是第一種左邊加右邊減去中間,還有就是兩邊都有的情況,兩邊滿足迴文,中間也滿足迴文就行了,所以是dp[ i+1 ] [ j-1 ],還有隻有s[ i ]和s[ j ],也是迴文串,還有再加1。


#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;

const int mod = 10007;

int dp[1010][1010];
char str[1010];

int main()
{
    int T; scanf("%d",&T);
    for(int tt=1;tt<=T;tt++)
    {
        scanf("%s",str+1);
        int len = strlen(str+1);
        for(int i=1;i<=len;i++) dp[i][i] = 1;
        for(int l=1;l<=len;l++){
            for(int i=1;i<=len;i++){
                int j = i+l-1;
                if(j>len) continue;
                dp[i][j] = (dp[i+1][j]+dp[i][j-1]-dp[i+1][j-1]+mod)%mod;
                //dp[i+1][j-1],當i+1>j-1,dp爲0,不影響
                if(str[i]==str[j]) dp[i][j] = (dp[i][j]+dp[i+1][j-1]+1)%mod;
            }
        }
        printf("Case %d: %d\n",tt,dp[1][len]);

    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章