HDU 1513 Palindrome

Palindrome


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.
 
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算法,线把原串倒过来,求最大公共子序列,然后用总数减,由于最大有5000,数组太大会超内存,所一数组开2*5000的,所有i对2取余计算。 

#include
#include
#include
using namespace std;
char str1[5005],str2[5002];
short dp[2][5005];
int  main()
{
    int len,i,j;
    while(~scanf("%d",&len))
    {
        scanf("%s",str1+1);
        for(i=1;i<=len;i++)
        str2[len-i+1]=str1[i];
        for(i=0;i<=len;i++)
        {
            dp[0][i]=0;
            dp[1][0]=0;
        }
        for(i=1;i<=len;i++)
        for(j=1;j<=len;j++)
        {
            if(str1[i]==str2[j])
            dp[i%2][j]=dp[(i-1)%2][j-1%2]+1;
            else if(dp[(i-1)%2][j]>=dp[i%2][j-1])
            dp[i%2][j]=dp[(i-1)%2][j];
            else
            dp[i%2][j]=dp[i%2][j-1];
        }
        printf("%d\n",len-dp[len%2][len]);
    }
    return 0;
}


你可能感兴趣的:(ACM,DP,(DP)LCS与LIS)