HDU4632-Palindrome subsequence(区间DP)

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的回文子串的种类:
(1).如果str[i]==str[j],dp[i][j]=dp[i][j-1]+dp[i+1][j]-dp[i+1][j-1]+dp[i+1][j-1]+1;
(2).如果str[i]!=str[j],dp[i][j]=dp[i][j-1]+dp[i+1][j]-dp[i+1][j-1];

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#define N 1005
#define MOD 10007

using namespace std;

int dp[N][N];

int main()
{
	string str;
	int T,len;
	scanf("%d",&T);
	for(int t=1;t<=T;t++)
	{
		cin>>str;
		memset(dp,0,sizeof(dp));
		len=str.length();
		for(int i=1;i<=len;i++)
		{
			dp[i][i]=1;
		}
		for(int i=1;i<=len;i++)
		{
			for(int j=1;j+i-1<=len;j++)
			{
				int end=j+i-1;
				if(str[end-1]==str[j-1])
					dp[j][end]=(dp[j+1][end]+dp[j][end-1]+1)%MOD;
				else
					dp[j][end]=(dp[j+1][end]+dp[j][end-1]-dp[j+1][end-1]+MOD)%MOD;
			}
		}
		printf("Case %d: %d\n",t,dp[1][len]);
	}
	return 0;
 } 

猜你喜欢

转载自blog.csdn.net/weixin_43357583/article/details/105769709