Palindrome
Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 55248 | Accepted: 19105 |
Description
A palindrome is a symmetrical string, that is, a string read identically from left to right as well as from right to left. You are to write a program which, given a string, determines the minimal number of characters to be inserted into the string in order to obtain a palindrome.
As an example, by inserting 2 characters, the string "Ab3bd" can be transformed into a palindrome ("dAb3bAd" or "Adb3bdA"). However, inserting fewer than 2 characters does not produce a palindrome.
As an example, by inserting 2 characters, the string "Ab3bd" can be transformed into a palindrome ("dAb3bAd" or "Adb3bdA"). However, inserting fewer than 2 characters does not produce a palindrome.
Input
Your program is to read from standard input. The first line contains one integer: the length of the input string N, 3 <= N <= 5000. The second line contains one string with length N. The string is formed from uppercase letters from 'A' to 'Z', lowercase letters from 'a' to 'z' and digits from '0' to '9'. Uppercase and lowercase letters are to be considered distinct.
Output
Your program is to write to standard output. The first line contains one integer, which is the desired minimal number.
Sample Input
5 Ab3bd
Sample Output
2
题目大意:
求最少需要添加几个字母才能使得原串变成一个回文串。
分析:
本题可以利用动态规划来解,首先必须推出一个公式: 需要添加最少字母数 = 原串长度 - 原串和其逆串的最长公共子串长度。由于本题原串范围为2500,如果用普通的二维数组来存的话是要超内存的,所以必须采用滚动数组来做,由于当前状态只由上一个状态决定,所以滚动数组用2*2500表示即可。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int inf = 0xfffffff;
const int maxn = 5002;
char str1[maxn];
char str2[maxn];
int roll[2][maxn];
int main()
{
int m;
int i;
int j;
while(cin>>m)
{
for(i=1; i<=m; i++)
{
cin>>str1[i];
}
str1[m+1] = '\0';
for(j=m; j>=1; j--)
{
str2[j] = str1[m-j+1];
}
str2[m+1] = '\0';
for(i=1;i<=m;i++)
{
roll[0][i] = 0;
roll[1][i] = 0;
}
roll[0][0] = roll[1][0] = 0;
int max_len = -inf;
for(i=1; i<=m; i++)
{
for(j=1; j<=m; j++)
{
if(str1[i] == str2[j])
{
roll[i % 2][j] = roll[(i-1) % 2][j-1] + 1;
}
else
{
roll[i % 2][j] = max(roll[(i-1) % 2][j],roll[i % 2][j-1]);
}
if(roll[i % 2][j] > max_len)
{
max_len = roll[i % 2][j];
}
}
}
cout<<m - max_len<<endl;
}
return 0;
}