Palindrome
Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 61160 | Accepted: 21317 |
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
题解:给定一个字符串L,为了保证L是回文序列需要最少添加几个字符;
做法是得到L的逆序列S,求L和S的最长公共子序列,用到动态规划的知识,如果运用maxlen[i][j]=max(maxlen[i-1][j], maxlen[i][j-1])会爆内存,所以用滚动数组来实现,因为当我们用完maxlen[i][j]后就用一次,所以可以把5000*5000的数组缩小到2*5000。
如下代码:
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
char L[5050], S[5050];
int maxl[2][5050];
int main()
{
int n,i,j;
while(cin>>n)
{
for(i=1; i<=n; i++)
cin>>L[i];
L[n+1]='\0';
for(i=1; i<=n; i++)
S[i]=L[n-i+1];
memset(maxl,0,sizeof(maxl));
int e=0;///设置滚动数组
for(i=1; i<=n; i++)
{
e=1-e;
for(j=0; j<=n; j++)
{
if(L[i]==S[j])
maxl[e][j]=maxl[1-e][j-1]+1;
else
maxl[e][j]=maxl[e][j-1]>maxl[1-e][j]?maxl[e][j-1]:maxl[1-e][j];
}
}
cout<<n-maxl[e][n]<<endl;
}
return 0;
}