【Manacher算法】求最长回文串的优秀算法

先贴一下代码~

//by 减维
#include<cstdio>
#include<iostream>
#include<cstring>
#include<queue>
#include<cstdlib>
#include<ctime>
#include<cmath>
#include<algorithm>
#define ll long long
#define maxn
using namespace std;

char s[10000015],a[10000015];
int nxt[10000015],mr,pos,ans;

int main()
{
    char ch=getchar();
    a[0]='#';a[1]='#';
    gets(s+1);int ls=strlen(s+1);
    for(int i=1;i<=ls;++i)a[i*2]=s[i],a[i*2+1]='#';int n=ls*2+2;
    for(int i=1;i<=n;++i){
        if(mr>i)nxt[i]=min(nxt[2*pos-i],mr-i);
        else nxt[i]=1;
        while(a[i-nxt[i]]==a[i+nxt[i]])nxt[i]++;
        if(i+nxt[i]>mr)mr=i+nxt[i],pos=i;
        ans=max(ans,nxt[i]-1);
    }
    printf("%d",ans);
}

 

posted @ 2017-10-17 18:18  减维  阅读(146)  评论(0编辑  收藏  举报