回文串数dp(uvaAgain Palindromes )

来源:互联网 发布:乐视视频显示网络异常 编辑:程序博客网 时间:2024/05/22 13:21

Problem I

Again Palindromes

Input: Standard Input

Output: Standard Output

Time Limit: 2 Seconds

 

A palindorme is a sequence of one or more characters that reads the same from the left as it does from the right. For example,Z, TOT and MADAM are palindromes, butADAM is not.

 

Given a sequence S of N capital latin letters. How many ways can one score out a few symbols (maybe 0) that the rest of sequence become a palidrome. Varints that are only  different by an order of scoring out should be considered the same.

 

Input

The input file contains several test cases (less than 15). The first line contains an integerT that indicates how many test cases are to follow.

 

Each of the T lines contains a sequence S (1≤N≤60). So actually each of these lines is a test case.

 

Output

For each test case output in a single line an integer – the number of ways.

      

Sample Input                             Output for Sample Input

3

BAOBAB

AAAA

ABA

22

15

5

题意:给定一个字符串,然后可以删除一些字符形成回文串,问有多少种删除方法

思路:dp[i][j]表示区间(i,j)有多少个回文串。如果s[i]==s[j],那么要加上(i+1,j),(i,j-1)之间的回文串,因为两个都计算了(i+1,j-1)的串,所以要减掉,s[i],s[j]跟(i+1,j-1)之间的回文串也可以组成回文串,所以要加上

#include<iostream>#include<cstdio>#include<string>#include<cstring>#include<vector>#include<cmath>#include<queue>#include<stack>#include<map>#include<set>#include<algorithm>using namespace std;typedef long long LL;const int maxn=70;int N;char s[maxn];LL dp[maxn][maxn];LL DP(int l,int r){    if(dp[l][r]!=-1)return dp[l][r];    if(l>r)return dp[l][r]=0;    if(l==r)return dp[l][r]=1;    LL &ans=dp[l][r];    ans=0;    if(s[l]==s[r])ans=DP(l+1,r)+DP(l,r-1)+1;    else ans=DP(l+1,r)+DP(l,r-1)-DP(l+1,r-1);    return ans;}int main(){    int T;    scanf("%d",&T);    while(T--)    {        scanf("%s",s);        memset(dp,-1,sizeof(dp));        int len=strlen(s);        printf("%lld\n",DP(0,len-1));    }    return 0;}







0 0