G - 回文串
Time Limit:3000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u
Submit Status

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
题目大意:一串字符,从左往右读和从右往左读是完全一样的。
解题思路:
这个题目可以转化为求最长公共子串的问题,就是将原字符串逆转,然后求原字符串和逆转字符串的最长公公子串,最后要注意c数组要定义成short型,否则会超内存

程序代码:
 1 #include<cstdio>
 2 #include <cstring>
 3 using namespace std;
 4 #define MAX 5010
 5 char a[MAX],b[MAX];
 6 short c[MAX][MAX];
 7 int max(int x,int y)
 8 {
 9     return x>y?x:y;
10 }
11 int main()
12 {
13     int n;
14     scanf("%d",&n);
15     scanf("%s",a);
16     for(int i=n-1;i>=0;i--)
17         b[n-i-1]=a[i];
18         b[n]='\0';
19     memset(c,0,sizeof(c));
20     for(int i=0;i<n;i++)
21         for(int j=0;j<n;j++)
22     {
23         if(a[i]==b[j])
24             c[i+1][j+1]=c[i][j]+1;
25         else
26             {
27                 if(c[i+1][j]>c[i][j+1])
28                     c[i+1][j+1]=c[i+1][j];
29                 else  c[i+1][j+1]=c[i][j+1];
30             }
31     }
32     printf("%d\n",n-c[n][n]);
33 
34 return 0;
35 }
View Code