1. 程式人生 > >1040 Longest Symmetric String(manacher演算法模板)

1040 Longest Symmetric String(manacher演算法模板)

Given a string, you are supposed to output the length of the longest symmetric sub-string. For example, given Is PAT&TAP symmetric?, the longest symmetric sub-string is s PAT&TAP s, hence you must output 11.

Input Specification:

Each input file contains one test case which gives a non-empty string of length no more than 1000.

Output Specification:

For each test case, simply print the maximum length in a line.

Sample Input:

Is PAT&TAP symmetric?

Sample Output:

11

 

#include<iostream>
#include<cmath>
#include<string.h>
#include<algorithm>
#include<cstdio>
#include<queue>
#include<set>
#include<map>
#include<vector>
#include<string>
using namespace std;
typedef long long ll;
/*1暴力
int main(){
    string s;
    int maxlen = 0;
    getline(cin,s);
    for(int i = 0; i < s.size(); i++)
    {
        for(int j = i+1;j<=s.size();j++)
        {
            string s1 = s.substr(i,j),s2 = s1;
            reverse(s2.begin(),s2.end());
            if(s2==s1&&maxlen<s1.size())
                maxlen=s1.size();
        }
    }
    printf("%d",maxlen);
}*/
//2.manacher演算法
const int maxn = 100005;
int n,ans,length[maxn<<1];
string a;char s[maxn<<1];
void init(){
    s[0] = '$';
    for(int i = 1; i <= n+1;i++)
    {
        s[2*i-1] = '#';
        s[2*i] = a[i-1];
    }
    n = n*2+2;
}
void manacher(){
    int mx = 0 , mid = 0;
    ////mx為目前最長迴文子串的右端點 mid為mx對應迴文子串的中點
    for(int i = 1; i < n ; i++)
    {
        if(i < mx)
            length[i] = min(mx-i,length[2*mid-i]);
        else
            length[i] = 1;
            while(s[i-length[i]]==s[i+length[i]])
            {
                length[i]++;
                if(length[i]+i>mx)
                {
                    mx = length[i]+i;
                    mid = i;
                }
            }
    }
}
int main(){
    getline(cin,a);
    //scanf("%s",a);
    n = a.length();
    init();
    manacher();
    for(int i = 0; i < n ; i++)
    {
        ans = max(ans,length[i]);
    }
    printf("%d",ans-1);
    return 0;
}