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
 
插入几个字符使原本的串成为回文串
View Code
 1 #include<stdio.h>
2 #include<stdlib.h>
3 #include<math.h>
4 #include<string.h>
5 char str[5010], str1[5010];
6 int dp[3][5010];
7
8 int max( int x, int y )
9 {
10 return x>y?x:y;
11 }
12
13 int main()
14 {
15 int n, k;
16 while( scanf( "%d", &n ) == 1 )
17 {
18 scanf( "%s", str );
19 k = 0;
20 for( int i = n-1; i >= 0; i-- )
21 str1[k++] = str[i];
22 memset( dp, 0, sizeof(dp) );
23 for( int i = 0; i < n; i++ )
24 for( int j = 0; j < k; j++ )
25 {
26 if( str[i] == str1[j] )
27 dp[(i+1)%2][j+1] = dp[i%2][j]+1;
28 else
29 {
30 dp[(i+1)%2][j+1] = max(dp[i%2][j+1],dp[(i+1)%2][j]);
31 }
32 }
33 printf( "%d\n", n-dp[n%2][k]);
34 }
35 }

posted on 2012-03-29 13:44  狸の舞  阅读(109)  评论(0编辑  收藏  举报