uva 10617 - Again Palindrome

来源:互联网 发布:微信运动添加数据来源 编辑:程序博客网 时间:2024/06/06 04:23

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