求一个串需要添加多少个字符才能变成回文。
思路: 求出这个串与他的反串的最大公共子序列, 其实这个序列就是最大的已存在的回文数。 然后用总的数量减之即可
Palindrome
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. 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 <stdio.h> #include <string.h> #include <iostream> using namespace std; #define N 5050 char g[N],g1[N]; int dp[2][N]; int main() { int n; scanf("%d",&n); scanf("%s",g+1); int cnt=0; for(int i=n;i>=1;i--) { g1[i]=g[++cnt]; } int a=0,b=1; for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { if(g[i] == g1[j]) { dp[b][j]=dp[a][j-1]+1; } else dp[b][j]=max(dp[b][j-1],dp[a][j]); } swap(a,b); } printf("%d\n",n-max(dp[0][n],dp[1][n])); return 0; }