题目链接:点击打开链接
Time Limit: 2 second(s) | Memory Limit: 32 MB |
By definition palindrome is a string which is not changed when reversed. "MADAM" is a nice example of palindrome. It is an easy job to test whether a given string is a palindrome or not. But it may not be so easy to generate a palindrome.
Here we will make a palindrome generator which will take an input string and return a palindrome. You can easily verify that for a string of length n, no more than (n - 1) characters are required to make it a palindrome. Consider "abcd" and its palindrome "abcdcba" or "abc" and its palindrome "abcba". But life is not so easy for programmers!! We always want optimal cost. And you have to find the minimum number of characters required to make a given string to a palindrome if you are only allowed to insert characters at any position of the string.
Input
Input starts with an integer T (≤ 200), denoting the number of test cases.
Each case contains a string of lowercase letters denoting the string for which we want to generate a palindrome. You may safely assume that the length of the string will be positive and no more than 100.
Output
For each case, print the case number and the minimum number of characters required to make string to a palindrome.
Sample Input | Output for Sample Input |
6 abcd aaaa abc aab abababaabababa pqrsabcdpqrs | Case 1: 3 Case 2: 0 Case 3: 2 Case 4: 1 Case 5: 0 Case 6: 9 |
题解:添加的最少字符不就是 = 该字符串的长度 - 该字符串与它的倒序串的最长公共子串
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int n;
char a[110],b[110];
int dp[110][110]; // dp[i][j]=k 表示长度为 i的串1与长度为 j的串2的最长公共子串的长度为 j
int main()
{
int text=0;
scanf("%d",&n);
while(n--)
{
scanf("%s",a);
int len=strlen(a);
for(int i=0;i<len;i++)
b[i]=a[len-i-1];
memset(dp,0,sizeof(dp));
for(int i=1;i<=len;i++)
{
for(int j=1;j<=len;j++)
{
if(a[i-1]==b[j-1])
dp[i][j]=dp[i-1][j-1]+1;
else
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
}
}
printf("Case %d: %d\n",++text,len-dp[len][len]);
}
return 0;
}