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 testcase.
Output
For each test case output in a single line an integer — the number of ways.
Sample Input
3 BAOBAB AAAA ABA
Sample Output
22 15 5
#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main(){
int t;
cin>>t;
while(t--){
char s[65];
ll dp[65][65];
cin>>s;
int len=strlen(s);
for(int i=0;i<len;i++){
for(int j=0;j<len;j++){
if(i==j) dp[i][j]=1;
else dp[i][j]=0;
}
}
for(int i=1;i<len;i++){
for(int j=0,k=i;k<len;j++,k++){
dp[j][k]=dp[j+1][k]+dp[j][k-1];
if(s[j]==s[k]){
dp[j][k]+=1;
}
else dp[j][k]-=dp[j+1][k-1];
}
}
cout<<dp[0][len-1]<<endl;
}
return 0;
}
想到动态规划,可是不是很熟练。不会。每一个都可以是回文串,所以有两个下标,求得是一段。中间的回文串在两边相等时,还可以构成,数量与减的重复的一致。这个靠感觉,认真推一下呗。动态规划,以前面的推到后面的,那么小推大,同时结合最小的单元是长度为3。我一开始想的是一次加一个,但是加了一个可以与一段内部再组成回文串,不仅仅只是一个单独,和一个和一段整体是不是回文串。
那么就要用到一个和一段为整体,是不可分割的,又结合对称性,内部和外部可能构成回文串,但是只加一个是不太可能的,要用到里面的回文串,这样才是dp嘛,而且也不是很优美,一段有两头,于是从两边着手。