POJ1159 Palindrome

Palindrome
Time Limit: 3000MS   Memory Limit: 65536K
Total Submissions: 44576   Accepted: 15197

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

这道题先求最字符串与其逆序字符串的最长公共子序列的长度,然后用源长度相减得结果。
但是题目要求字符串最大长度为5001,开个5001*5001的二维数组会RE
上网查了下别人的方法,又涨了个新姿势:滚动数组 
因为只要求最长公共子序列的长度,所以建立的存过程的数组中c[i][j]只跟c[i-1][]的结果有关,所以将滚动数组开为c[2][5001] i++的时候做模2运算即可
c[i%2]的上一组是c[1-i%2]
 
#include<stdio.h>
#include<string.h>
void adb(char str1[],char str2[])                                                 //adb的意思是a倒b..原谅我起函数名字的时候不知道想什么
{
    int len1=strlen(str1)-1;
    for(int i=0;i<=len1;i++)
    {
        str2[i]=str1[len1-i];
    }
} 

int main()
{
    int n;
    scanf("%d",&n);
    char str1[5001],str2[5001];
    scanf("%s",str1);
    adb(str1,str2);
    int len=strlen(str1);
    int c[2][5001];                                                               //用c[5001][5001]会Runtime Error所以用滚动数组 
    int last;
    for(int i=0;i<=1;i++)                                                        
    {
        for(int j=0;j<=len;j++)c[i][j]=0;
    }
    for(int i=1;i<=len;i++)                                
    {
        for(int j=1;j<=len;j++)                                                   //滚动数组用模2运算,使得每次循环在C[0]和C[1]中进行 
        {
             if(str1[i-1]==str2[j-1])                                             //为什么可以用滚动数组呢,因为不用求出LCS的坐标,只要知道最后结果就行 
            {
                c[i%2][j]=c[1-i%2][j-1]+1;
            }                                                                     //而过程中c[i][j]的值只与c[i-1]相关,所以可以用滚动数组 
            else if(c[1-i%2][j]>=c[i%2][j-1])                                   
            {
                c[i%2][j]=c[1-i%2][j];
            }
            else c[i%2][j]=c[i%2][j-1];
            last=i%2;
        }
    }
    int minmove=len-c[last][len];
    printf("%d\n",minmove);
    return 0;
}

 

posted on 2012-11-28 16:24  Aquariuslt  阅读(173)  评论(0)    收藏  举报

导航