UVA 10617 Again Palindrome

来源:互联网 发布:caj转word转换器 mac 编辑:程序博客网 时间:2024/06/15 14:05

原题:
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 le contains several test cases (less than 15). The rst 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.
SampleInput
3
BAOBAB
AAAA
ABA
SampleOutput
22
15
5
大意:
给你一个字符串,问你这个字符串去掉0个或者多个字符串后能形成的回文字符串的个数。

#include <bits/stdc++.h>using namespace std;//fstream input,output;string s;long long dp[61][61];int main(){    ios::sync_with_stdio(false);//  input.open("in.txt");//  output.open("out.txt");    int t;    cin>>t;    while(t--)    {        cin>>s;        int len=s.size();        memset(dp,0,sizeof(dp));        for(int i=1;i<=len;i++)        dp[i][i]=1;        for(int l = 2;l<=len;l++)        {            for(int i=1;i<=len-l+1;i++)            {                int j=i+l-1;                if(s[i-1]==s[j-1])                    dp[i][j]=dp[i+1][j]+dp[i][j-1]+1;                else                    dp[i][j]=dp[i+1][j]+dp[i][j-1] - dp[i+1][j-1];            }        }        cout<<dp[1][len]<<endl;    }//  input.close();//  output.close();    return 0;}

解答:
之前有个回文串的动态规划问题没想出来,这回涨经验了。考虑回文串的结构可以知道如果要用动态规划的思想去判断或者思考一种双向增长的问题,那么多数都是区间dp。此题也是如此,回文串要从两端比较,现在设置状态dp[i][j]表示字符串从第i个字母到第j个字母之间形成的字符串能有多少回文串。现在考虑状态转移:

//现在假定要判断字母i到字母j之间有多少个回文//YXXXXXXXZ Y代表第i个字母,X代表i+1到j-1之间字母,Z为第j个字母//i.......j现在分别考虑第i个字母和第j个字母,可知,dp[i][j]应该由dp[i+1][j]与dp[i][j-1]这两个值的状态转移过来。如图

这里写图片描述
如果dp[i][j]=dp[i+1][j]+dp[i][j-1],由简单的容斥原理知道中间的部分相当于被多加了一次,所以dp[i][j]=dp[i+1][j]+dp[i][j-1]-dp[i+1][j-1],表示为第i到第j个字符之间能组成的回文数等于第i+1个字符到第j个字符与第i个字符到第j-1个字符的和再减去重复的部分。
不过这是在字母s[i]与字母s[j]不相同的情况下的方程,如果字母s[i]与s[j]相等,那么一个回文串的开头和结尾加上相同的字母肯定也是回文串,则相当于考虑在保留字母i和字母j的情况下把i+1到j-1之间的字符再算一次。所以转移方程在字母i和字母j相等的情况下为
dp[i][j]=dp[i][j-1]+dp[i+1][j]-dp[i+1][j-1]+dp[i+1][j-1]+1化简为
dp[i][j]=dp[i][j-1]+dp[i+1][j]+1即可。

0 0
原创粉丝点击