Palindrome(poj3974)(manacher算法)
http://poj.org/problem?id=3974
Palindrome
Time Limit: 15000MSMemory Limit: 65536K
Total Submissions: 2707Accepted: 995
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
Source
Seventh ACM Egyptian National Programming Contest
解析:
题意:求最长回文串长度:
思路:
利用manacher算法计算;
这里简要概述一下这个算法;
总的来说是相邻字符中间插入一个相同的字符构成一新的字符(以此可以避免奇偶性讨论。),然后求以每个点为中心的回文字长度。
就这以下标号来解释一下:
p[i]:以第i个字符为中心的回文长度;
id:前一个回文中心.
mx:前一个回文的最有右端 ,mx=p[id]+id;
1.逐次枚举i判断是否在mx前面,更新p[i]初值;
2.左右看扩展,求当前最大的p[i];
3.更新 id,mx;
4得出的结果为ans=max{p[i]-1};
Accepted580K 47MSG++ 740B
*/
#include<stdio.h> #include<string.h> #include<algorithm> #include<algorithm> using namespace std; const int maxn=1000000+10; char s[maxn],st[maxn*2]; int p[maxn*2]; void manacher() { int i,j,len; len=strlen(s); for(i=0,j=0;i<len;i++,j+=2)//构造新数组 { st[j]='#'; st[j+1]=s[i]; } st[2*len]='#';//末尾处不可忽略 int mx=0,id; for(i=1;i<=2*len;i++) { if(mx>i)//如果此时的中心点仍在前一个回文串中 {p[i]=min(p[2*id-i],mx-i); } else p[i]=1; //由中心向两边扩展 for(;st[i-p[i]]==st[i+p[i]]&&(i-p[i]>=0)&&(i+p[i]<=2*len);p[i]++) if(mx<i+p[i])//更新mx,id; { id=i; mx=i+p[i]; } } int ans=0; for(i=1;i<=len*2;i++)//得到最长回文字 { if(p[i]>ans) ans=p[i]; } printf("%d\n",ans-1); } int main() { int ca=0; while(scanf("%s",s)!=EOF) { if(strcmp(s,"END")==0) break; printf("Case %d: ",++ca); manacher(); } return 0; }