zoukankan      html  css  js  c++  java
  • Manacher算法

    Manacher

    可以在(O(n))的时间内求一个字符串的最长回文子串。

    教学视频链接

    例题

    HDU - 3068

    #include <bits/stdc++.h>
    
    #define FOPI freopen("in.txt", "r", stdin)
    #define FOPO freopen("out.txt", "w", stdout)
    #define FOR(i,x,y) for (int i = x; i <= y; i++)
    #define ROF(i,x,y) for (int i = x; i >= y; i--)
    
    using namespace std;
    typedef long long LL;
    const int inf = 0x3f3f3f3f;
    const int maxn = 2e5 + 100;
    
    char Ma[maxn*2];
    int Mp[maxn*2];
    
    void Manacher(char s[], int len)
    {
        int l = 0;
        Ma[l++] = '$';
        Ma[l++] = '#';
        FOR(i, 0, len-1) Ma[l++] = s[i], Ma[l++] = '#';
        Ma[l] = 0;
    
        int mx = 0, id = 0;
        FOR(i, 0, l-1)
        {
            Mp[i] = mx > i ? min(Mp[2*id-i], mx-i) : 1;
            while(Ma[i+Mp[i]] == Ma[i-Mp[i]]) Mp[i]++;
            if (i+Mp[i] > mx) mx = i+Mp[i], id = i;
        }
    }
    
    char s[maxn];
    int main()
    {
        while(~scanf("%s", &s))
        {
            int len = strlen(s);
            Manacher(s, len);
            int ans = 0;
            FOR(i, 0, 2*len+2-1) ans = max(ans, Mp[i]-1);
            printf("%d
    ", ans);
        }
    }
    
    
  • 相关阅读:
    codevs 1450 xth 的旅行
    Loj #6287 诗歌
    Codeforces 323C Two permutations
    Spoj MKTHNUM
    [TJOI2015]弦论
    Spoj SUBLEX
    bzoj 4338: BJOI2015 糖果
    bzoj 3462: DZY Loves Math II
    bzoj 2843: 极地旅行社
    清北学堂模拟赛d4t5 b
  • 原文地址:https://www.cnblogs.com/ruthank/p/10910527.html
Copyright © 2011-2022 走看看