多敲几个模板题,加深一下对Manacher算法的理解。
这道题给的时间限制15s,是我见过的最长的时间的了。看来是为了让一些比较朴素的求最大回文子串的算法也能A过去
Manacher算法毕竟给力,运行时间200+MS
//#define LOCAL
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std; const int maxn = + ;
char s1[maxn], s2[maxn * ];
int p[maxn * ]; void Init(void)
{
s2[] = '$', s2[] = '#';
int j = ;
for(int i = ; s1[i] != '\0'; ++i)
{
s2[j++] = s1[i];
s2[j++] = '#';
}
s2[j] = '\0';
} void manacher(char s[])
{
int id, mx = ;
p[] = ;
for(int i = ; s[i] != '\0'; ++i)
{
if(mx > i)
p[i] = min(p[id*-i], mx-i);
else
p[i] = ;
while(s[i + p[i]] == s[i - p[i]])
++p[i];
if(i + p[i] > mx)
{
mx = i + p[i];
id = i;
}
}
} int getans(void)
{
int ans = ;
for(int i = ; s2[i] != '\0'; ++i)
ans = max(ans, p[i] - );
return ans;
} int main(void)
{
#ifdef LOCAL
freopen("3974in.txt", "r", stdin);
#endif int kase = ;
while(scanf("%s", s1) != EOF)
{
if(s1[] == 'E') break;
Init();
manacher(s2);
printf("Case %d: %d\n", kase++, getans());
}
return ;
}
代码君