洛谷P3805 【模板】manacher

题目链接:https://www.luogu.com.cn/problem/P3805

manacher算法模板题。

参考资料:https://oi-wiki.org/string/manacher/

示例程序:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 2.2e7 + 5;

int n;
char s[maxn/2], a[maxn];
int p[maxn];

void init() {
    int m = 0;
    a[m++] = '$';
    a[m++] = '#';
    for (int i = 0; i < n; i++)
        a[m++] = s[i], a[m++] = '#';
    a[m++] = '^';
    n = m;
}

void manacher() {
    int mr = 0, mid;
    for (int i = 1; i < n; i++) {
        if (i < mr) p[i] = min(p[mid * 2 - i], mr - i);
        else p[i] = 1;
        while (a[i - p[i]] == a[i + p[i]]) p[i]++;
        if (i + p[i] > mr)
            mr = i + p[i], mid = i;
    }
}

int main() {
    scanf("%s", s);
    n = strlen(s);

    init();
    manacher();

    int res = 0;
    for (int i = 0; i < n; i++)
        res = max(res, p[i]);
    printf("%d\n", res - 1);

    return 0;
}
posted @ 2023-10-31 15:49  quanjun  阅读(22)  评论(0编辑  收藏  举报