hdu 1513

来源:互联网 发布:c语言default什么意思 编辑:程序博客网 时间:2024/05/22 08:14

题意:给你一个长度为n的字符串,求出最少加多少字符才能使成为回文串。

我们可以把str1倒过来,得到str2。那么str1和str2的Lcs就是他们之间的最大不需要修改的值。也就是说,那些值原本是不需要动的。只是因为缺少一些必要的字符,只要加上他们str1就和str2相等了。n - LCS的长度,就是缺少的必要字符的值,就是答案。



#include<cstdio>#include<algorithm>#include<cstring>using namespace std;const int maxn = 5000 + 5;long long d[3][maxn];char str[maxn];int main(){    int n;    while(scanf("%d", &n) == 1)    {        memset(d, 0, sizeof(d));        scanf("%s", str);        int temp;        for(int i = 0; i < n; i++)        {            temp = i & 1;            for(int j = 0; j < n; j++)            {                if(str[i] == str[n - j - 1]) d[temp][j + 1] = d[temp^1][j] + 1;                else d[temp][j + 1] = max(d[temp][j], d[temp^1][j + 1]);            }        }        printf("%lld\n", n - d[temp][n]);    }    return 0;}


原创粉丝点击