Palindrome
Time Limit: 15000MS Memory Limit: 65536K
Total Submissions: 17178 Accepted: 6614

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

题目大意:
给你一个长度为1E6的字符串问你最长的回文串长度是多少?
思路:
O(n)的马拉车板子题,马拉车的主要思想就是在O(n^2)的基础上进行改善,O(n ^ 2)是枚举这个字符,然后从中心扩展求最长回文串,而马拉车对于已经知道的最长回文串,根据左边可以推测出右边的信息从而减少没必要的比较,这就是马拉车的思想,实现马拉车需要一个当前最大回文长度下标id和id所对应的最大右界。另外马拉车对字符串的预处理也很好的解决的奇偶回文串的问题。

代码:

#include<stdio.h>
#include<string.h>
#include<algorithm> 
const int maxn=3e6+10;
char t[maxn],s[maxn];
int p[maxn];
int len1,len2;
template<class T>
T min(T a,T b){
	return a>b?(b):(a);
} 
template<class T>
T max(T a,T b){
	return a>b?(a):(b);
} 
void init(){
	s[0]='@';
	s[1]='#';
	for(int i=0;i<len1;i++){
		s[i*2+2]=t[i];
		s[i*2+3]='#';
	}
	len2=len1*2+2;
	s[len2]='$';
}
void mancher(){
	int id=0,mx=0;
	p[0]=0;
	for(int i=1;i<len2;i++){
		if(mx>i){
			p[i]=min(mx-i,p[2*id-i]);
		}else{
			p[i]=1;
		}
		while(s[i+p[i]]==s[i-p[i]])p[i]++;
		if(i+p[i]>mx){
			mx=i+p[i];id=i;
		}
	}
}
int main(){
	int k=1;
	while(scanf("%s",t)&&t[0]!='E'){
		len1=strlen(t);
		init();
		mancher();
		int maxlen=0;
		for(int i=0;i<len2;i++){
			maxlen=max(maxlen,p[i]);
		}
		printf("Case %d: ",k++);
		printf("%d\n",maxlen-1);
	}
}