1. 程式人生 > >poj 1159 Palindrome(最長公共子序列+滾動陣列)

poj 1159 Palindrome(最長公共子序列+滾動陣列)

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. 
InputYour 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.OutputYour 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
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define LL long long
#define inf 0x3f3f3f3f

char s1[5005];
char s2[5005];
int n;
int  lc[2][5005];

int Max(int x,int y)
{
    return x>y?x:y;
}
int solve()//求lcs的過程
{
    for(int i=1;i<=n;i++)//因為每次只用到了上一排,所以只儲存兩行就好了。
    {
        for(int j=1;j<=n;j++)
        {
            if(s1[i]==s2[j])
            {
                lc[i%2][j]=lc[(i-1)%2][j-1]+1;
            }
            else if(s1[i]!=s2[j])
            {
                lc[i%2][j]=Max(lc[(i-1)%2][j],lc[i%2][j-1]);
            }
        }
    }
}

void Reverse(char *p)
{
    for(int i=1;i<=n;i++)
    {
        s2[n-i+1]=s1[i];
    }
}
int main()
{

    while(cin>>n)
    {
        memset(lc,0,sizeof(lc));
        scanf("%s",s1+1);
        Reverse(s1);
        solve();
        printf("%d\n",n-max(lc[1][n],lc[0][n]));//最大值可能在這兩個之中。
    }

}

參考:https://blog.csdn.net/lyy289065406/article/details/6648163