0
点赞
收藏
分享

微信扫一扫

POJ1159 Palindrome(滚动数组DP)


Palindrome


Time Limit: 3000MS

 

Memory Limit: 65536K

Total Submissions: 60017

 

Accepted: 20898


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


这道题的题意是给出一个字符串,如果要是它添加字符成为回文串的话,添加的最少的字符是多少个。

用dp的思想求出它的最长回文子序列,用串的长度减去子序列的长度就是添加的最少字符。

如果单纯的用dp[n][n]来写会爆内存因为给的数据中n会给很大导致出现很多不必要的数据,此时利用滚动数组,每计算两个便覆盖数据,大大的节省了空间。

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
#define N 10000
char a[N];
char b[N];
int dp[3][N];

int main()
{
int i,j,n,m;
cin>>n;
for(i=1;i<=n;i++)
{
cin>>a[i];
b[n-i+1]=a[i];
}
memset(dp,0,sizeof(dp));
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
if(a[i]==b[j])
{
dp[i%3][j]=dp[(i-1)%3][j-1]+1;
}
else
{
dp[i%3][j]=max(dp[(i-1)%3][j],dp[i%3][j-1]);
}
}
cout<<n-dp[n%3][n]<<endl;
return 0;
}



举报

相关推荐

0 条评论