| Time Limit: 15000MS | Memory Limit: 65536K | |
| Total Submissions: 11080 | Accepted: 4212 |
Description
A string is said to be a palindrome if it reads the same both forwards and backwards, for example "madam" is a palindrome while "acm" is not.
The students recognized that this is a classical problem but couldn't come up with a solution better than iterating over all substrings and checking whether they are palindrome or not, obviously this algorithm is not efficient at all, after a while Andy raised his hand and said "Okay, I've a better algorithm" and before he starts to explain his idea he stopped for a moment and then said "Well, I've an even better algorithm!".
If you think you know Andy's final solution then prove it! Given a string of at most 1000000 characters find and print the length of the largest palindrome inside this string.
Input
Output
Sample Input
abcbabcbabcba abacacbaaaab END
Sample Output
Case 1: 13 Case 2: 6
Source
manacher算法详解参考博客:https://blog.youkuaiyun.com/dyx404514/article/details/42061017
https://segmentfault.com/a/1190000008484167#articleHeader2
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define mem(a,b) memset(a,b,sizeof(a))
const int mm=1000005;
char a[mm],tmp[mm*2];
int p[mm*2];
int init()
{
int la=strlen(a);
tmp[0]='$'; //最左端分界符
tmp[1]='#'; //字母之间的分隔符
int j=2;
for(int i=0;i<la;i++)
{
tmp[j++]=a[i]; //转换字符串
tmp[j++]='#';
}
tmp[j]='\0';
return j;
}
int mach()
{
int len=init();
int id,mx=0,maxx=-1; //id是最大回文字串中心,mx是回文字串能延伸到最右端的位置。
for(int i=1;i<len;i++)
{
if(mx>i)
p[i]=min(p[2*id-i],mx-i);
else
p[i]=1; //i>=mx
while(tmp[i-p[i]]==tmp[i+p[i]])
p[i]++;
if(mx<p[i]+i)
{
id=i; //更新id,mx的值;
mx=p[i]+i;
}
maxx=max(maxx,p[i]-1);
}
return maxx;
}
int main()
{
int ca=1;
while(~scanf("%s",a))
{
if(!strcmp(a,"END"))
break;
else
printf("Case %d: %d\n",ca++,mach());
mem(p,0);
}
return 0;
}
348



被折叠的 条评论
为什么被折叠?



