2013多校联合4 1001 Palindrome subsequence(hdu 4632)

http://acm.hdu.edu.cn/showproblem.php?pid=4632


Palindrome subsequence

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/65535 K (Java/Others)
Total Submission(s): 483    Accepted Submission(s): 169


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, 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]=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,注意边界特判一下就可以了,代码如下。



#include <iostream>
#include <string.h>
#include <stdio.h>
#include <algorithm>
#define maxn 1010
#define mod 10007
#define ll long long
using namespace std;
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]=dp[l][r]+dfs(l+1,r-1)+1;
    while(dp[l][r]>=mod)
    dp[l][r]-=mod;
    while(dp[l][r]<0)
    dp[l][r]+=mod;
    return dp[l][r];
}
int main()
{
   // freopen("dd.txt","r",stdin);
    int ncase,time=0;
    scanf("%d",&ncase);
    while(ncase--)
    {
        printf("Case %d: ",++time);
        scanf("%s",str+1);
        int i,j,len=strlen(str+1);
        for(i=0;i<=len;i++)
        {
            for(j=0;j<=len;j++)
            dp[i][j]=-1;
        }
        printf("%d\n",dfs(1,len));
    }
    return 0;
}


你可能感兴趣的:(2013多校联合4 1001 Palindrome subsequence(hdu 4632))