A graph Manacher algorithm to calculate the longest palindrome substring of a string
Title Link: http://acm.hdu.edu.cn/showproblem.php?pid=3068
Problem description gives a string s that consists only of lowercase English characters a,b,c...y,z, seeking the length of the longest palindrome in S.
Palindrome is the same as the inverse of the string, such as ABA, ABBA, etc.
Input has multiple sets of case, no more than 120 groups, each set of input is a line of lowercase English characters a,b,c...y,z string s
Between two sets of case separated by a blank line (the empty line is not processed)
String length len <= 110000
Output an integer x for each row, corresponding to a set of case, representing the longest palindrome length contained in the string for the group case.
Sample Input
Aaaaabab
Sample Output
43
Code:
#include <iostream> #include <cstring>using namespace std;string s;int p[110050*2]; It is important to note that the length of the array is greater than twice times the length of the string;//Convert the string to an odd string void init () {memset (p,0,sizeof (p)); String s1= "$"; for (int i=0;i<s.size (); i++) {s1+= ' # '; S1+=s[i]; } s1+= ' # '; S=S1;} Calculated P[id] indicates the ID position of the palindrome radius void Manacher () {int id=0; The right edge of the ID position is most right (within the known range); int mx=0; The right boundary position of the ID; for (int i=1;i<s.size (); i++) {if (mx>i) p[i]=min (p[2*id-i],mx-i); else p[i]=1; for (; S[i-p[i]]==s[i+p[i]];p [i]++); if (I+P[I]>MX) {mx=i+p[i]; Id=i; }}}int Main () {Cin.sync_with_stdio (false); while (cin>>s) {init (); Manacher (); int ans=0; for (int i=1;i<s.size (); i++) {if (Ans<p[i]) ans=p[i]; } cout<<ans-1<<endl; } return 0;}
Longest palindrome string HDU3068 longest palindrome "Manacher algorithm"