Palindrome
Description
Andy the smart computer science student was attending an algorithms class when the professor asked the students a simple question, “Can you propose an efficient algorithm to find the length of the largest palindrome in a string?”
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
Your program will be tested on at most 30 test cases, each test case is given as a string of at most 1000000 lowercase characters on a line by itself. The input is terminated by a line that starts with the string “END” (quotes for clarity).
Output
For each test case in the input print the test case number and the length of the largest palindrome.
Sample Input
abcbabcbabcba
abacacbaaaab
END
Sample Output
Case 1: 13
Case 2: 6
【解题报告】
题目大意是求一个字符串的最长回文子串的长度。
我们考虑用Manacher算法来解决。
那么Manacher是什么呢?
首先。
我们考虑用没有出现过的字符‘#’来表示原串的间隔,如:
ababa ->#a#b#a#b#a#。
这样就将回文中心是字符和字符间隔两种情况统一起来了。
▪而为了避免溢出(因为’\0’==‘\0’),再在串头串尾加上没有出现过的不同的字符,如’+’,‘-’之类的,即变为了+#a#b#a#b#a#-。现在对这个串做manacher求以每个字符(除+和-)为中心的最长回文串即可。
思想:从左向右求出以每个位置为中心点的最长回文串长度,对于每个位置利用之前的信息来快速得到答案。均摊O(N)。那么如何利用之前信息呢?
▪我们利用的信息是之前处理得到的,向右延伸最远的回文串(即右端点最靠右),令其回文中心下标为id,右端为mx。令pal[i]表示以i为中心的回文串的右端到中心i 的长度。
▪现在考虑对于一个位置i,求pal[i]。考虑两种情况。[YYR良心作图]
▪此时可得pal[i] = pal[2*id-i];
▪此时可得pal[i] ≥ mx-i+1。
▪由于是大于等于,那么从pal[i]=mx-i+1 开始,暴力判断pal[i]能到多少。
注意每次判断成功都会使得mx++,失败则结束。由于mx是单增的,于
是判断成功次数不超过串长次,于是均摊复杂度为O(n)。
▪另外还有一种情况:mx < i,但实际上可以归入情况2中。
代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define N 1000010
int pal[N<<1];
char a[N],s[N<<1];
int cas=0;
int manacher()
{
int len=strlen(a);
int ret=0,id=0,mx=0;
for(int i=1;i<=len;++i) s[i<<1]=a[i-1],s[i<<1|1]='#';
len<<=1,len+=1;
s[0]='+',s[1]='#',s[len+1]='#',s[len+2]='-';
for(int i=1;i<=len;++i)
{
if(mx>i) pal[i]=min(mx-i,pal[id*2-i]);
else pal[i]=1;
while(s[i-pal[i]]==s[i+pal[i]]) ++pal[i];
if(mx<pal[i]+i) mx=pal[i]+i,id=i;
ret=max(ret,pal[i]);
}
return ret-1;
}
int main()
{
while(scanf("%s",a))
{
if(a[0]=='E'&&a[1]=='N'&&a[2]=='D') break;
printf("Case %d: %d\n",++cas,manacher());
}
return 0;
}