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
/*
2500W*4字节
一亿字节 10WKB。。我用short int的。过了。。。不过内存还是将近5W。。有用滚动数组的。内存压缩到280K。。。。。ORZ。。。
*/
#include <iostream>
#include <cstdio>
using namespace std;
#define maxn 5008
char A[maxn];
char B[maxn];
short int dp[maxn][maxn];
inline short int max1(short int a, short int b)
{
return a>b?a:b;
}
inline short int max(short int a, short int b,short int c)
{
if(a<b)a=b;
if(a<c)a=c;
return a;
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
cin>>A;
for(int i=0;i<n;i++)
{
B[i]=A[n-i-1];
}
B[n]='\0';
dp[0][0]=(A[0]==B[0]);
for(int i=1;i<n;i++)
{
dp[i][0]=max1(dp[i-1][0],A[i]==B[0]);
}
for(int i=1;i<n;i++)
{
dp[0][i]=max1(dp[0][i-1],A[0]==B[i]);
}
for(int i=1;i<n;i++)
{
for(int j=1;j<n;j++)
{
dp[i][j]=max(dp[i-1][j],dp[i][j-1],short int (dp[i-1][j-1]+(A[i]==B[j])));
}
}
cout<<n-dp[n-1][n-1]<<endl;
}
return 0;
}
接下来的做法是用滚动数组做的。空间复杂度骤降280K。
下面这个和上面这个也是有略微不同的,下面我是从1开始的。上面我是从0开始的。。想一想建议写成从1开始的,0开始的需要特殊初始化。
#include <iostream>
#include <cstdio>
using namespace std;
inline int max(int a,int b)
{
return a>b?a:b;
}
inline int max(int a,int b,int c)
{
if(a<b)a=b;
if(a<c)a=c;
return a;
}
int main()
{
int n;
while(scanf("%d",&n)==1)
{
char * A=new char[n+1];
char * B=new char[n+1];
cin>>A;
for(int i=0;i<n;i++)
{
B[i]=A[n-i-1];
}
int ** dp=new int* [n+1];
dp[0]=new int [n+1];
dp[1]=new int [n+1];
dp[0][0]=0;
for(int i=1;i<n;i++)
{
dp[0][i]=0;
}
dp[1][0]=0;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
dp[i%2][j]=max(dp[(i-1)%2][j],dp[i%2][j-1],dp[(i-1)%2][j-1]+(A[i-1]==B[j-1]));
}
}
int len=n-max(dp[1][n],dp[0][n]);
cout<<len<<endl;
delete A;
delete B;
delete dp;
}
return 0;
}