http://poj.org/problem?id=1159
题意:给一个长度为n的串,求将其变成回文要增加的最少字符数.
思路:LCS算法:状态方程:if(a[i]==b[j]) ans[i][j]=max1(ans[i-1][j-1]+1,ans[i-1][j],ans[i][j-1]); else ans[i][j]=max(ans[i-1][j],ans[i][j-1]);
二维数组的形式(必须用short,否则超内存):
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
short ans[5010][5010];
int max1(int a,int b,int c)
{
if(a<b)
a=b;
if(a<c)
a=c;
return a;
}
int main()
{
int n,i,j;
char a[5010],b[5010];
while(scanf("%d",&n)!=EOF)
{
scanf("%s",a+1);
for(i=1;i<=n;i++)
b[n-i+1]=a[i];
for(i=0;i<=n;i++)
ans[i][0]=ans[0][i]=0;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(a[i]==b[j])
ans[i][j]=max1(ans[i-1][j-1]+1,ans[i-1][j],ans[i][j-1]);
else
ans[i][j]=max(ans[i-1][j],ans[i][j-1]);
printf("%d\n",n-ans[n][n]);
}
return 0;
}
一维数组:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int ans1[5010],ans2[5010];
int max1(int a,int b,int c)
{
if(a<b)
a=b;
if(a<c)
a=c;
return a;
}
int main()
{
int n,i,j;
char a[5010],b[5010];
while(scanf("%d",&n)!=EOF)
{
scanf("%s",a+1);
for(i=1;i<=n;i++)
b[n-i+1]=a[i];
for(i=0;i<=n;i++)
ans1[i]=ans2[i]=0;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
if(a[i]==b[j])
ans2[j]=max1(ans1[j-1]+1,ans1[j],ans2[j-1]);
else
ans2[j]=max(ans1[j],ans2[j-1]);
for(j=1;j<=n;j++)
{
ans1[j]=ans2[j];
ans2[j]=0;
}
ans1[0]=ans2[0]=0;
}
printf("%d\n",n-ans1[n]);
}
return 0;
}