Palindrome
Time Limit: 3000MS   Memory Limit: 65536K
Total Submissions: 43759   Accepted: 14920

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

思路1:对称,从动态规划来讲就是自下而上的方法,现在下面是求子结构的过程:

str[N]为字符串,dp[i][j]表示从i个字符到j个字符之间要对称,需要插入最少个字符是多少;

如果str[i]==str[j],则dp[i][j]=dp[i+1][j-1]; (i<=j<=n);

如果str[i]!=str[j],则dp[i][j]=1+min{dp[i][j-1],dp[i+1][j]},亦即从子结构中找最小的插入字符数;

代码:

#include<stdio.h>
#include<string.h>
#define N 5001
#define MIN(a,b) (a<b?a:b)
short dp[N][N];
int n;
char s[N];

int main()
{
  scanf("%d",&n);
 
     scanf("%s",s+1);
  for(int i=1;i<=n;i++)
   for(int j=1;j<=n;j++)
    dp[i][j]=0;
  for(int i=n-1;i>=1;i--)
  {
     for(int j=i;j<=n;j++)
  {
    if(s[i]==s[j])
    dp[i][j]=dp[i+1][j-1];
    else
    dp[i][j]=MIN(dp[i+1][j],dp[i][j-1])+1;   
     }   
     }         
     printf("%d\n",dp[1][n]);

  return 0;
}

思路2:把字符串str看为两个字符串,一个为正向,另一个为反向,通过正反找出最长公共子序列的长度为m,说明给定的正向字符串中的如果要构成对称的,最多左右两边对应的字符就有n个,接下来剩下的n-m个字符是需要添加字符使之对称的,即需要添加n-m个字符

代码:

int main()
{
  scanf("%d",&n);
  scanf("%s",s+1);
  memset(dp,0,sizeof(dp));
  for(int i=1;i<=n;i++)
   ss[n+1-i]=s[i];
   for(int i=1;i<=n;i++)
   {
      for(int j=1;j<=n;j++)
   {
      if(s[i]==ss[j])
   dp[i][j]=dp[i-1][j-1]+1;
   else
   dp[i][j]=MAX(dp[i-1][j],dp[i][j-1]);    
   }    
   } 
   printf("%d\n" , n-dp[n][n] );
   //system("pause");
   return 0;
}


链接:http://poj.org/problem?id=1159