hihocoder1032(最長迴文子串manacher算法)

題目連接:點擊打開鏈接


解題思路:

manacher算法的模板題。


完整代碼:

#include <algorithm>
#include <iostream>
#include <cstring>
#include <complex>
#include <cstdio>
#include <string>
#include <cmath>
#include <queue>
using namespace std;
typedef unsigned long long LL;
const int MOD = int(1e9)+7;
const int INF = 0x3f3f3f3f;
const double EPS = 1e-9;
const double PI = acos(-1.0); //M_PI;
const int maxn = 2000001;
int n;
char s[maxn] , t[maxn];
int len[maxn];


void manacher(char t[])
{
    int t_len = strlen(t);
    int mx = 0 , id;
    for(int i = 1 ; i < t_len ; i ++)
    {
        if(mx > i)  len[i] = min(len[id * 2 - i] , mx - i);
        else    len[i] = 1;
        while(t[i + len[i]] == t[i - len[i]])     len[i] ++;
        if(len[i] + i > mx)
        {
            mx = len[i] + i;
            id = i;
        }
    }
}


void solve(char s[])
{
    int s_len = strlen(s);
    int t_len = s_len * 2 + 2;
    t[0] = '+';
    for(int i = 0 ; i < t_len ; i ++)
    {
        t[i * 2 + 1] = '#';
        t[i * 2 + 2] = s[i];
    }
    manacher(t);
    int ans = -INF;
    for(int i = 1 ; i < t_len ; i ++)
        ans = max(ans , len[i]);
    printf("%d\n" , ans - 1);
}

int main()
{
    #ifdef DoubleQ
    freopen("in.txt","r",stdin);
    #endif
    while(~scanf("%d",&n))
    {
        for(int i = 0 ; i < n ; i ++)
        {
            scanf("%s" , s);
            solve(s);
        }
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章