Palindrome
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 3919 Accepted Submission(s): 1341
Problem 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嗯,题目大意就是说,给一字符串,往里面添加字符使其成为回文串,问最少添加几个可使其成为回文串。嗯,看题之后就感觉是把字符串反转之后再lcs,当时就开的dp[5050][5050]然后就内存超限了,看了讨论区里人家用dp[2][5050]存的,然后自己拿纸再那模拟,发现当前值只与上一行上一列和上一行当前列和当前行上一列有关,然后就自己写了一遍因为我从1开始存不细心还WA了一遍#include <iostream> #include<cstdio> #include<cstring> #define len 5050 using namespace std; char s1[len],s2[len]; int dp[2][len]; int maxi(int a,int b) { return a>b?a:b; } int main() { int n,k; while(~scanf("%d",&n)) { memset(dp,0,sizeof(dp)); scanf("%s",s1); strcpy(s2,s1); strrev(s2); k=1; for(int i=1;i<=n;++i) { for(int j=1;j<=n;++j) { if(s1[i-1]==s2[j-1]) dp[k][j]=dp[!k][j-1]+1;//上一行上一列 else dp[k][j]=maxi(dp[!k][j],dp[k][j-1]); } k=!k;//最后一次循环k值又变了 } printf("%d\n",n-dp[!k][n]);//这里要把k值再变回来 } return 0; }