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, Z, TOT 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 |
解决方案:这题就是求该串字符能够组成不同回文串的种数,位置不同也当做两个不同类型的回文串。这题想了许久,wa了几遍,看了别人的代码才把思路给理清了。
若word[i]==word[j],则回文又多一个,所以dp[i][j]+=dp[i+1][j-1]+1;
若word[i]!=word[j],则dp[i][j]=dp[i+1][j]+dp[i][j-1]-dp[i+1][j-1];应为dp[i+1][j]和dp[i][j-1]的情况都包含了dp[i+1][j-1]的情况。
边界条件为dp[i][i]=1;
code:
#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char text[100];
long long dp[100][100];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%s",text+1);
int len=strlen(text+1);
memset(dp,0,sizeof(dp));
for(int i=1; i<=len; i++)
{
dp[i][i]=1;
}
for(int i=1; i<=len; i++)
{
for(int j=1; j+i<=len; j++)
{
if(text[j]==text[j+i])
{
dp[j][j+i]+=1+dp[j+1][j+i-1];
}
dp[j][j+i]+=dp[j+1][j+i]+dp[j][j+i-1]-dp[j+1][j+i-1];
}
}
printf("%lld\n",dp[1][len]);
}
return 0;
}