洛谷_P3805 【模板】manacher 算法

P3805 【模板】manacher 算法

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

string s,ts;
vector<int> len;

void init()
{
    ts.clear();
    ts+='@';
    for( int i=0;i<s.size();i++ )
    {
        ts+='#'; ts+=s[i];
    }
    ts+="#$";

    len.clear();
    len.resize( ts.size(),0 ); 
}

int manacher()
{
    int ans,yy,mid,i;
    ans=yy=mid=0;

    for( i=1;i<=ts.size()-2;i++ )
    {
        if( yy>i )  len[i]=min( yy-i,len[2*mid-i] );
        else        len[i]=1;

        while( ts[i-len[i]]==ts[i+len[i]] ) len[i]++;

        if( i+len[i]>yy ) { yy=len[i]+i; mid=i; }
        ans=max( ans,len[i] );
    } 
    return ans-1;
}

int main()
{
    while( cin>>s )
    {
        init();
        cout<<manacher()<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_63173957/article/details/124953963
今日推荐