链接:
http://poj.org/searchproblem?field=source&key=IOI+2000
题意:
至少增添多少个字符可以使原字符串变成回文串
思路:
原字符串反转,求最长公共子序列长度,剩余的长度就是需要加的字符数
这里用到了滚动数组,因为该次的dp其实只取决去前一次的dp
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int dp[2][5010];
string s1,s2;
int main()
{
int n;
cin>>n;
cin>>s1;
s2=s1;
reverse(s2.begin(),s2.end());
memset(dp,0,sizeof dp);
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
{
if(s1[i-1]==s2[j-1])
dp[i%2][j]=dp[(i-1)%2][j-1]+1;
else
dp[i%2][j]=max(dp[i%2][j-1],dp[(i-1)%2][j]);
}
int ans = dp[n%2][n];
cout<<n-ans<<endl;
return 0;
}