PalindromeTime
limit:15000MS
Memory Limit:65536KB
64bit IO Format:%i64d &%i6 4u SubmitStatus
Description
Andy the smart Computer Science student is attending a algorithms class when the professor asked the students a simple q Uestion, "Can propose an efficient algorithm to find the length of the largest palindrome in a string?"
A string is said to being a palindrome if it reads the same both forwards and backwards, for example ' Madam ' is a palindrome While the "ACM" is not.
The students recognized that's a classical problem but couldn ' t come up with a solution better than iterating over a ll substrings and checking whether they be palindrome or not, obviously this algorithm was not efficient at all, after a W Hile 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 know Andy's final solution then prove it! Given a string of 1000000 characters find and print the length of the largest palindrome inside this string.
Input
Your program would be tested on at the most of the test cases, each test case is given as a string of in most 1000000 lowercase cha Racters on a line by itself. The input is terminated by a line, 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
1#include <cstdio>2#include <cstring>3#include <cstdlib>4#include <algorithm>5 using namespacestd;6 Const intmaxn=1000000+Ten;7 //Manacher Algorithm8 Const intlen=MAXN;9 Const intn=len*2;Ten intP[n]; One CharStr[len],tmp[n]; A //P[i] Indicates the longest length of the palindrome extending to the right, centered on Str[i] - voidManacher (Char* STR,int*p) - { the intn=strlen (str), I, ID, MX; - for(p[mx=id=0]=i=1; i<n; i++) - { -P[i]=mx>i?min (p[2*id-i], mx-i+1):1; + while(i+p[i]<n&&i-p[i]>=0&&str[i+p[i]]==str[i-p[i]]) p[i]++; - if(mx<i+p[i]-1) + { AId=i; atmx=i+p[i]-1; - } - } - } - //The length of the longest palindrome of Str - intMaxpalindrome (Char*str) in { - intans=0; to inti, N; + for(i=0, N=strlen (str); i<n; i++) - { thetmp[2*i]='#'; *tmp[2*i+1]=Str[i]; $ }Panax Notoginsengtmp[2*i]='#'; -tmp[2*i+1]=' /'; then=n*2+1; + manacher (TMP, p); A for(i=0; i<n; i++) the { + if(Ans < p[i]-1) - { $Ans = p[i]-1; $ } - } - returnans; the } - intMain ()Wuyi { the intI=1; - for(i=1;; i++) Wu { -scanf"%s", str); About Chars[]= {'E','N','D',' /'}; $ if(strcmp (str,s) = =0) - Break; - Else -printf"Case %d:%d\n", I,maxpalindrome (str)); A } + return 0; the}
Palindrome (Longest palindrome string manacher algorithm) O (n)