腾讯2017暑期实习生编程题-A-构造回文

来源:互联网 发布:java calendar c# Date 编辑:程序博客网 时间:2024/05/13 06:19

ACM模版

描述

描述

题解

很久很久以前,大概是去年这个时候,在51上做过一道求原串如何删除才能使得回文串最长,输出最长长度。相比这个问题,不过是少了一步,只需再多一步总数-最长回文串长度即可,至于最长回文串长度只需要将原串逆序排列,然后求原串与逆序串的最长公共子序列即可,即 LCS 问题。

代码

#include <iostream>#include <algorithm>#include <cstring>using namespace std;const int MAXN = 1010;int a[MAXN][MAXN];int LCS(const char *s1, const char *s2){   //  s1:0...m, s2:0...n    int m = (int)strlen(s1), n = (int)strlen(s2);    int i, j;    a[0][0] = 0;    for (i = 1; i <= m; ++i)    {        a[i][0] = 0;    }    for (i = 1; i <= n; ++i)    {        a[0][i] = 0;    }    for (i = 1; i <= m; ++i)    {        for (j = 1; j <= n; ++j)        {            if (s1[i - 1] == s2[j - 1])            {                a[i][j] = a[i - 1][j - 1] + 1;            }            else if (a[i - 1][j] > a[i][j - 1])            {                a[i][j]= a[i - 1][j];            }            else            {                a[i][j] = a[i][j - 1];            }        }    }    return a[m][n];}int main(){    char s[MAXN], s_[MAXN];    while (~scanf("%s", s))    {        int len = (int)strlen(s);        for (int i = 0; i < len; i++)        {            s_[len - i - 1] = s[i];        }        cout << len - LCS(s, s_) << '\n';    }    return 0;}

参考

《最长公共子序列》

0 0
原创粉丝点击