1. http://poj.org/problem?id=1159
题意:给定一个字符串,求最少插入多少字符使该字符串变成回文字符串。
分析:
方法1:先求该字符串与其逆序列的最长公共子序列LCS(该部分已经回文),则原字符串长度减去LCS长度即为需要插入的字符数。
方法2::(算法导论习题15.2 最长回文子序列)
i=j时,LPS(i,j)=1;i<j时,LPS(i,j)=0;
以“BBABCBCAB”为例:
#include<iostream>
#include<string>
using namespace std;
const int maxn=5005;
int dp[2][maxn];//滚动数组
string str;
int main()
{
int n;
cin>>n;
cin>>str;
for(int i=n-1;i>=0;i--)
{
dp[i&1][i]=1;
for(int j=i+1;j<n;j++)
if(str[i]==str[j])
dp[i&1][j]=dp[(i+1)&1][j-1]+2;
else
dp[i&1][j]=max(dp[