POJ1159——Palindrome(最长公共子序列+滚动数组)

时间:2022-09-20 10:53:48

Palindrome

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

题目大意:

    给定一个字符串,判断最少需要添加几个字符使其变成回文。

解题思路:

    回文定义:一个字符串与该字符串的逆序相同。

    则显然该题求得是:字符串长度-字符串与其逆序的最长公共子序列长度

    字符串有5000位,若使用一般的LCS需要开5000*5000的数组。(数组过大)

    所以需要使用滚动数组。(LCS每行更新的时候只需要根据上一行的数据即可) 只需要开辟2*5000的数组。 ^_^

    LCS的dp方程:dp[i][j]=max( dp[i-1][j-1] + (a[i]==b[j]) , max( dp[i-1][j] , dp[i][j-1] ) )

Code:

 /*************************************************************************
> File Name: poj1159.cpp
> Author: Enumz
> Mail: 369372123@qq.com
> Created Time: 2014年10月27日 星期一 20时44分15秒
************************************************************************/ #include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<list>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
#include<cmath>
#include<bitset>
#include<climits>
#define MAXN 5001
using namespace std;
char a[MAXN], b[MAXN];
int dp[][MAXN];
int main()
{
int N;
while(cin>>N)
{
for (int i=;i<=N;i++)
{
scanf("%c",&a[i]);
b[N-i+]=a[i];
}
memset(dp,,sizeof(dp));
for (int i=;i<=N;i++)
{
dp[][]=dp[][];
for (int j=;j<=N;j++)
{
int tmp=max(dp[][j-],dp[][j]);
if (a[j]==b[i])
tmp=max(tmp,dp[][j-]+);
dp[][j]=tmp;
}
for (int i=;i<=N;i++)
dp[][i]=dp[][i];
}
cout<<dp[N][N]<<endl;
}
return ;
}