您的位置:首页 > 大数据 > 人工智能

回文串数dp(uvaAgain Palindromes )

2015-03-14 16:09 435 查看

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, but
ADAM 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 integer
T 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: