【HDU 3068】 最长回文

【题目链接】

           http://acm.hdu.edu.cn/showproblem.php?pid=3068

【算法】

          Manacher算法求最长回文子串

【代码】

          

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

char s[MAXN];

inline void Manacher()
{
        int i,len,ans = 0,pos = 0,mx = 0;
        static char tmp[MAXN<<1];
        static int p[MAXN<<1];
        len = strlen(s+1);
        for (i = 1; i <= len; i++) 
        {
                tmp[2*i-1] = '#';
                tmp[2*i] = s[i];
        }
        tmp[len = 2 * len + 1] = '#';
        for (i = 1; i <= len; i++)
        {
                if (mx > i) p[i] = min(p[2*pos-i],mx-i);
                else p[i] = 1;
                while (i - p[i] >= 1 && i + p[i] <= len && tmp[i-p[i]] == tmp[i+p[i]]) p[i]++;
                if (i + p[i] - 1 > mx)
                {
                        mx = i + p[i] - 1;
                        pos = i;        
                } 
        }
        for (i = 1; i <= len; i++) ans = max(ans,p[i]-1);
        printf("%d\n",ans);
}

int main() 
{
        
        while (scanf("%s",s+1) != EOF) Manacher();        
        
        return 0;
    
}

猜你喜欢

转载自www.cnblogs.com/evenbao/p/9248798.html