Manacher O(n) 回文字符串查找算法

虽然在题目中, 这类算法出现得比较少,
但其效率的确很好并且不是很难懂, 所以学一下也总有用得到的时候;

下面是一篇不错的博客, 推荐;

http://www.open-open.com/lib/view/open1419150233417.html
for(; s[i - len[i]] == s[i + len[i]]; len[i]++);
并说明一下, 有些读者认为这句话没有意义但实际上
我们设当前正匹配i位置, 找到的最远的地方max_dist(即当前找出的longest回文串所到达的地方)设中心点为id,max_dist 的对应点Min_dist,
i关于id对应的点是j, 所以我们用j来更新len【i】, 有的读者可能认为只要len【j】正确, 计算len【i】是不需要这句话的。
其实不然, 因为如果回文串的部分超过min_dist的话是无法保证超出的部分在id的另一侧是对称的, 所以这一句话相当有必要;
给出裸题
HDU 3068代码

#include <bits/stdc++.h>
using namespace std;

#define N 110005
#define rep(i, s, t) for(int i = s, end = t; i <= end; ++i)

struct Manacher{
    int len, p[N<<1], res = -1;
    char s[N<<1], str[N];
    void read() {
        res = -1;
        len = strlen(str);
        s[0] = '$';
        rep(i, 0, len - 1)
            s[i<<1|1] = '#', s[(i+1)<<1] = str[i];
        s[len<<1|1] = '#';
    }

    void match() {
        int Max_dist = 0, id;
        rep(i, 1, len<<1|1) {
            if(Max_dist > i) p[i] = min(Max_dist - i, p[2*id-i]);
            else p[i] = 1;
            for(; s[i - p[i]] == s[i + p[i]]; p[i]++);
            if(p[i] + i >Max_dist) Max_dist = p[i] + i, id = i;
        }
    }

    int solve() {
        read();

        match();

        rep(i, 1, len<<1|1)
            res = max(res, p[i] - 1);
        return res;
    }
}M;

int main() {
#ifndef ONLINE_JUDGE
    freopen("data.in", "r", stdin);
    freopen("result.out", "w", stdout);
#endif
    while(scanf("%s", M.str) != EOF){
        printf("%d
", M.solve());
    }
    return 0;
}
原文地址:https://www.cnblogs.com/pbvrvnq/p/8530168.html