Manacher algorithm Templates

Source: Internet
Author: User

Manacher template today took a palindrome, so under the guidance of 520 giant to learn a wave of manacher. First recommend a wave of 520 big guy's blog title description

A string s consisting of a lowercase English character a,b,c...y,z is given, and the length of the longest palindrome in S is obtained.

String length is n

Input/output format

Input format:

A line of lowercase English characters a,b,c...y,z a string s

Output format:

An integer representing the answer

Input/Output sample

Input Sample # #:

Aaa

Sample # # of output:

3

Description

String length len <= 11000000

Test instructions is the longest palindrome that requires a string.


First think about how the naïve algorithm is implemented: we can enumerate the beginning and end of a string, and then use \ (o (len) \) time to verify that the total time complexity is \ (o (n^3) \) .


According to the nature of the palindrome, we can not have to raise points and enumerate the end point, because Palindrome is about its symmetrical axis symmetry, so we can consider directly enumerate its symmetric axis, and then extend to both sides. This total time complexity is \ (O (n^2) \) .


because a string has at most only \ (len\) the axis of symmetry, so the same axis of symmetry of those palindrome can be expanded by this point of symmetry. But because the axis of symmetry is likely to be in the middle of two characters (that is, the length of the palindrome is even), this will make the next operation very inconvenient, so we will be the original string in the middle of every two characters into a special symbol for easy judgment, such as ' # ' or something. Make a chestnut:

Brave_Cattle   ->   #B#r#a#v#e#_#C#a#t#t#l#e#

such as this two T, it is obvious that their symmetric axis is between the two characters, then the insertion of the special symbol for us to judge a lot of things saved.


In order to find the longest palindrome string, we obviously ask for the largest palindrome radius of the one.
at this point we need an array \ (p[i]\) to record down from subscript \ (i\) Start to expand the number of palindrome radius. Because a special character is inserted in the middle of every two characters, the length of the longest string after all \ (p[i]\) is recorded as the largest \ (p[i]-1\) .


So the point is: How to quickly find the \ (p[i]\) array. we can see that If there is a palindrome string is a long palindrome string, then the length of the palindrome can be directly from the previous record of the symmetric axis on the other side of the symmetric string launched (this must look at the figure to understand).

We use the \ (id\) to indicate the subscript (that is, the subscript from subscript Greek Class) of the Palindrome's symmetric axis, which is currently the radius of the middle back \ (mx\) about \ (id\) The symmetric point to subscript \ (mx\) The palindrome string, \ (mx\) represents \ (p[id]\) , which is the rightmost subscript of the palindrome string. In the figure is the interval represented by the bottom line, which we call \ (a\) interval.

At this time there is a i\ string with a symmetric axis, that is, the range of intervals represented by the line below \ (i\) , we call it \ (i\) interval. According to the mathematical knowledge, we can get the \ (i\) about \ (id\) the symmetry point \ (j=id*2-i\)(if you do not know how to draw a root axis to simulate it), with this axis of symmetry to get the palindrome string we call it \ (j\) interval. because the \ (i,j\) interval is a palindrome string belonging to the \ (a\) interval, and they are symmetric about \ (id\) , the radius of the two intervals is the same length.

if(i < mx) p[i] = p[id*2-i];


But we also need to consider a situation: if the right end of the \ (i\) interval exceeds the \ (a\) interval, then the radius of the \ (i\) interval is not taken and \ (j\) Range as large as the radius , so we need to determine if this happens. For example:

if(i < mx) p[i] = min(p[pos*2-i],mx-i);


Of course, that's it. \ (p[i]\) also needs to be extended further, because there is a possibility that can be extended later. Determine if the string that is being processed is the first \ (i-p[i]\) bit and the \ (i+p[i]\) Bits are the same.

Finally, we need to update the palindrome as a long string in the loop. We want to pick the farthest one, because this will reduce the number of cycles.

Let's take a look at the code comment for the end point:

void manacher(){    int000;    for(int i=1;i<=cnt;i++){        if(i < mx) p[i] = min(p[pos*2-i],mx-i);//处理        else1;//否则以i为对称轴的这个串就属于长串的范围外,无法直接得到p[i]值.        while(ss[i+p[i]] == ss[i-p[i]]) p[i]++;//还要再扩展一次        if(mx < i+p[i]) mx = i+p[i], pos = i;//更新作为长串的回文串        ans = max(ans,p[i]-1);    }}

The content is about the same. If you don't understand it, you might just have to figure out a little bit more data to simulate this process.

Let's paste the complete code below.

#include <bits/stdc++.h>using namespaceStdConst intn=11000000+5;Const intinf=2147483647;intCNT, len, ans =0;CharS[n], ss[n*2];intp[n*2];voidInit () {//Insert one character per two charactersLen = strlen (s), CNT =1; ss[0] ='!'; SS[CNT] ='#'; for(intI=0; i<len;i++) ss[++cnt] = S[i], ss[++cnt] ='#';}voidManacher () {intpos =0, mx =0; for(intI=1; i<=cnt;i++) {if(i < MX) p[i] = min (p[pos*2-I],MX-I);ElseP[i] =1; while(Ss[i+p[i]] = = Ss[i-p[i]]) p[i]++;if(MX < i+p[i]) mx = i+p[i], pos = i; ans = max (Ans,p[i]-1); }}intMain () {scanf ("%s", s); Init ();    Manacher (); printf"%d\n", ans);return 0;}

Manacher algorithm Templates

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.