Palindrome
Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 51934 | Accepted: 17886 |
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
Source
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
char str1[100010],str2[100010];
int dp[2][5005];
int main()
{
int t,i,j;
while(cin>>t)
{
memset(dp,0,sizeof(dp));
int l=t;
for(i=0; i<t; i++)
{
cin>>str1[i];
str2[--l]=str1[i];
}
for(i=0; i<t; i++)
for(j=0; j<t; j++)
{
if(str1[i]==str2[j])
dp[i%2][j]=dp[(i-1)%2][j-1]+1;
else
dp[i%2][j]=max(dp[(i-1)%2][j],dp[i%2][j-1]);
}
cout<<t-dp[(t-1)%2][t-1]<<endl;
}
return 0;
}
眨一看这道题,感觉摸不着头脑,然后看了别人的题解才恍然大悟这是一道最长公共子序列的应用,感觉题目挺好的!
一定要注意数组的空间优化,如果开一个5000*5000的二维数组内存会超限,不信的可以提交试试看看!
这道题要用滚动二维数组来优化,你道题你只需要用到数组的上一个横行,所以只要开一个2*5000的数组就ok了,然后取mod2的值就可以循环了!