hihoCoder第一周---最长回文子串(1032)

其实这就是mancher算法的板子题,贴个代码好了。
思想请见我的另一篇博客:
https://blog.csdn.net/qq_41090676/article/details/86768361

#include <cstdio>
#include <cstring>
const int maxn = 3e6;
int len1,len2,p[maxn],ans;
char s[maxn], str[maxn];

int min(int x,int y)
{
    return x < y ? x : y;
}

void init()
{
    memset(p, 0, sizeof(p));
    str[0] = '$';
    str[1] = '#';
    for (int i = 0; i < len1;i++) {
        str[i * 2 + 2] = s[i];
        str[i * 2 + 3] = '#';
    }
    len2 = 2 * len1 + 2;
    str[len2] = '*';
    
}

void Mancher()
{
    int mx = 0, id = 0;
    for (int i = 1; i < len2;i++) {
        if (i<mx)
            p[i] = min(p[id * 2 - i], mx - i);
        else
            p[i] = 1;
        while (str[i-p[i]]==str[i+p[i]])
            p[i]++;
        if (p[i]+i>mx) {
            mx = p[i] + i;
            id = i;
        }
    }
}

int main()
{
    int n;
    scanf("%d", &n);
    while (n--) {
        scanf("%s", s);
        len1 = strlen(s);
        init();
        Mancher();
        ans = 0;
        for (int i = 1; i < len2;i++)
            if (p[i]>ans)
                ans = p[i];
        printf("%d
", ans - 1);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/xyqxyq/p/10366583.html