0
点赞
收藏
分享

微信扫一扫

poj Palindrome 3974 (字符串&manacher)


POJ - 3974


Palindrome



Submit Status




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



abcbabcbabcbaabacacbaaaabEND






Sample Output



Case 1: 13Case 2: 6



 




#include<stdio.h>
#include<string.h>
#define N 1000010
#include<algorithm>
using namespace std;
char s[N<<1];
char a[N];
int p[N<<1];
int manacher()
{
	int l=strlen(s),i;
	int r=1,m=1;
	int ans=0;
	memset(p,0,sizeof(p));
	p[1]=p[0]=1;
	for(i=2;i<l;i++)
	{
		if(r>i)
			p[i]=min(p[m*2-i],r-i);
		else
			p[i]=1;
		while(s[i-p[i]]==s[i+p[i]])
			p[i]++;
		if(p[i]+i>r)
		{
			r=p[i]+i;
			m=i;
		}
		ans=max(ans,p[i]);
	}
	return ans-1;
}
int main()
{
	int T=1;
	int i,j;
	while(scanf("%s",a)&&strcmp(a,"END"))
	{
		int l=strlen(a);
		s[0]='@';
		for(i=0;i<l;i++)
		{
			s[i*2+1]='#';
			s[i*2+2]=a[i];
		}
		s[i*2+1]='#';
		s[i*2+2]='\0';
		int ans=manacher();
		printf("Case %d: %d\n",T++,ans);
	}
	return 0;
}





Time Limit: 15000MS

 

Memory Limit: 65536KB

 

64bit IO Format: %I64d & %I64u

举报

相关推荐

0 条评论