Palindrome subsequence (区间dp)

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.

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

思路:注意到任意一个回文子序列收尾两个字符一定是相同的,于是可以区间dp,用dp[i][j]表示原字符串中[i,j]位置中出现的回文子序列的个数,有递推关系:

dp[i][j]=dp[i+1][j]+dp[i][j-1]-dp[i+1][j-1]

如果i和j位置出现的字符相同,那么dp[i][j]可以由dp[i+1][j-1]中的子序列加上这两个字符构成回文子序列,再加上i,j位置组成的回文子序列,也就是

dp[i][j]+=dp[i+1][j-1]+1,注意边界特判一下就可以了

但是需要注意的一点是这个题用地dfs写并不是特别优化,用c++提交可以过,中间的取模运算如果取模会超时,改成减法就可以过(虽然加减法比乘除快但是没想到时间卡的这么严?)否则会超时
code:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 1010;
const int mod = 10007;
int dp[maxn][maxn];
char str[maxn];
int dfs(int l,int r){
    if(l > r) return 0;
    if(l == r) return 1;
    if(dp[l][r] != -1) return dp[l][r];//记忆化搜索
    dp[l][r] = (dfs(l+1,r) + dfs(l,r-1) - dfs(l+1,r-1));
    if(str[l] == str[r]){
        dp[l][r] += (dfs(l+1,r-1) + 1);
        //相当于又可以以lr为两端和中间的所有已有回文序列构成新的回文序列
        //dfs(l+1,r-1)是两个端点和中间任意回文序列构成的新序列
        //+1是两个端点单独存在构成的一个长度为2的回文序列
    }
    while(dp[l][r] >= mod){
        dp[l][r] -= mod;//模运算改成减法运算
    }
    while(dp[l][r] < 0)
        dp[l][r] += mod;
    return dp[l][r];
}
int main(){
    int t;
    int cas = 0;
    scanf("%d",&t);
    while(t--){
        printf("Case %d: ",++cas);
        scanf("%s",str+1);
        int len = strlen(str+1);
        for(int i = 0; i <= len; i++){
            for(int j = 0; j <= len; j++){
                dp[i][j] = -1;
            }
        }
        printf("%d\n",dfs(1,len));
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/codeswarrior/article/details/80300458