Manacher 算法

 

回文串匹配!!!!NOIp回来在更。

#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cctype>

inline void read(int & x)
{
    x = 0;
    int k = 1;
    char c = getchar();
    while (!isdigit(c))
        if (c == '-') c = getchar(), k = -1;
        else c = getchar();
    while (isdigit(c))
        x = (x << 1) + (x << 3) + (c ^ 48),
        c = getchar();
    x *= k;
}

char s[11001010], S[33003030];
int l, len, f[33001010], p, ans;

void Manacher()
{
    int nowr = 1, nowm = 1; f[1] = 1;
    for (int i = 2; i <= len; ++i)
    {
        if (i > nowr) f[i] = 1;
        else p = (nowm << 1) - i, f[i] = std::min(f[p], (nowr - i) << 1 | 1);
        int x = (f[i] >> 1) + 1;
        while (i > x && i + x <= len && S[i + x] == S[i - x])
            ++x, f[i] += 2;
        if (i + x - 1 > nowr) nowr = i + x - 1, nowm = i;
        ans = std::max(ans, f[i]);
    }
}

signed main()
{
    scanf("%s", s + 1);
    l = strlen(s + 1); S[1] = '$'; 
    for (int i = 1; i <= l; ++i)
        S[i << 1] = s[i],
        S[i << 1 | 1] = '$';
    S[(l << 1) + 2] = '\0';
    len = strlen(S + 1);
    Manacher();
    printf("%d", ans >> 1);
    return 0;
}

 

posted @ 2018-11-08 12:44  Christopher_Yan  阅读(124)  评论(0编辑  收藏  举报