Again Palindromes

来源:互联网 发布:海信电视直播软件安装 编辑:程序博客网 时间:2024/06/10 18:08

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



//设f(i,j)表示f(i,j)删除一些字符之后是回文串的个数//然后可以得知当s[i]==s[j]时f(i,j)=f(i+1,j)+f(i,j-1)+1//当s[i]!=s[j]时f(i,j)=f(i+1,j)+f(i,j-1)-f(i+1,j-1)为什么//要减去呢,因为s[i]!=s[j]时删除(i+1,j-1)中的字符串最后得到的//不可能是回文串#include <cstdio>#include <cstdlib>#include <climits>#include <cstring>#include <iostream>#include <algorithm>#include <stack>#include <sstream>#include <string>#include <cmath>#include <queue>#include <map>#include <vector>#include <iomanip>#define cls(a,x) memset(a, x, sizeof(a))#define mkp make_pair;#define fir first;#define sec second;#define sf scanf#define pf printf#if(defined(_WIN32)||defined(__WIN32__))typedef __int64 LL;typedef unsigned __int64 ULL;#define ll I64#elsetypedef long long LL;typedef unsigned long long ULL;#define I64 ll#endifusing namespace std;typedef pair<int,int>pii;#define max(a,b) (a) > (b) ? (a) : (b)char s[70];LL f[70][70];LL dp(LL l, LL r){    if(l > r)        return 0;    if(l == r)        return 1;    LL &ans = f[l][r];    if(ans != -1)        return ans;    if(s[l] == s[r])    {        ans = dp(l, r - 1) + dp(l + 1, r) + 1;    }    else    {        ans = dp(l, r - 1) + dp(l + 1, r) - dp(l + 1, r - 1);    }    return ans;}int main(void){    int t;    cin>>t;    while(t--)    {        scanf("%s", s);        cls(f, -1);        int n = (int)strlen(s);        cout<<dp(0, n - 1)<<endl;    }    return 0;}





Russian Olympic Camp

0 0