uva 10617 - Again Palindrome

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, ZTOT andMADAM 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


这道题有了之前一道回文串的经验,开始独立思考,并解决了问题,虽然方法不是很地道,O(n^3),但毕竟是解决了问题。

dp[i][j]表示是s[i...j]得到回文串的方法数,现在决策s[j],删除s[j],那么dp[i][j]=dp[i][j-1];保留s[j],这样肯定得从s[i]找起,找到与位置k,使得s[k]==s[j],那么dp[i][j]+=dp[k+1][j-1]+1,

注意要+1,因为s[k]=s[j],所以中间可以是空串。

我是从区间长度为3开始递推的,自然k+2<=j,不要忘记k=j-1也可以啊,只是要特判,这是有两种情况s[j-1]==s[j],那么删除s[i...j-2]和s[i...j-1]两种方法均可,dp[i][j]+=2;

s[j-1]!=s[j],那么删除s[i...j-1],dp[i][j]+=1;


#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;

char s[70];
long long dp[70][70];
int main()
{
    int n;
    scanf("%d",&n);
    while(n--){
        scanf("%s",s);
        int len=strlen(s);
        for(int i=0;i<len;i++){
            dp[i][i]=1;
            if(s[i]==s[i+1]) dp[i][i+1]=3;
            else dp[i][i+1]=2;
        }
        for(int l=2;l<len;l++)
            for(int i=0,j=l;j<len;i++,j++){
                dp[i][j]=dp[i][j-1];
                for(int k=i;k+2<=j;k++)
                    if(s[k]==s[j]) dp[i][j]+=dp[k+1][j-1]+1;
                if(s[j-1]==s[j]) dp[i][j]+=2;
                else dp[i][j]+=1;
            }
        printf("%lld\n",dp[0][len-1]);
    }
	return 0;
}

其实网上还有O(n^2)解法:

直接从题意切入:dp[i, j]表示区间[i, j]最多有多少个这样的子串。

1. s[i] == s[j] 去掉s[i],则一个子问题就是dp[i+1, j],去掉s[j],另一个子问题就是dp[i, j-1]。

   显然这两个子问题是会有重叠的,比如去掉s[i], s[j]的dp[i+1, j-1]。

   如果s[i],s[j]都不去掉呢?则这个子问题的解显然是dp[i+1, j-1] + 1。

   于是会有 dp[i][j] = dp[i+1][j] + dp[i][j-1] + 1;

2. s[i] != s[j] 此时的子问题就比上述要简单了,因为s[i] s[j]与dp[i+1, j-1]的回文子串构成不了回文串。

   于是 dp[i][j] = dp[i+1][j] + dp[i][j-1] - dp[i+1][j-1];

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值