poj3974:Palindrome(manacher模板)

来源:互联网 发布:淘宝代刷自动返款系统 编辑:程序博客网 时间:2024/05/22 13:46

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

题意:
给一个字符串,求最长回文串。

题解:
Manacher模板,时间复杂度O(n)。

Manacher算法流程

在Manacher 算法中,我们添加两个辅助变量mx 和p,分别表示已有回文半径覆盖到的最右边界和对应中心的位置。
计算R[i]时,我们先给它一个下界,令i 关于p 的对称点j = 2p - i,分以下三种情况讨论:
(1) mx < i 时,只有R[i] >= 1
(2) mx − i > R[j] 时,以第j 位为中心的回文子串包含于以第p 位为中心的回文子串,由于i和j 关于p 对称,以第i 位为中心的回文子串必然也包含于以第p 位为中心的回文子串,故有R[i] = R[j]
(3) mx − i <= R[j] 时,以第j 位为中心的回文子串不一定包含于以第p 位为中心的回文子串,但由于i 和j 关于p 对称,以第i 位为中心的回文子串向右至少会扩展到mx 的位置,故有R[i] >= mx − i
对于超过下界的部分,我们只要逐位匹配就可以了。
由于逐位匹配成功必然导致mx 右移,而mx 右移不超过n 次,故Manacher 算法的时间复杂度为O(n).

代码:

#include<iostream>#include<cstdio>#include<cstdlib>#include<cstring>#include<string>#include<algorithm>#include<cmath>using namespace std;const int Maxn=1e6+50;char ch[Maxn*2],s[Maxn];int len,tt,tot,pos,id,ans,R[Maxn*2];inline void manacher(){    id=0,pos=0,ans=0;    int x=0;    for(int i=1;i<=tot;i++)    {        if(pos>i)x=min(pos-i,R[2*id-i]);        else x=1;        while(ch[i+x]==ch[i-x])++x;        if(i+x>pos)pos=i+x,id=i;        R[i]=x;        ans=max(R[i],ans);    }}int main(){    while(scanf("%s",s+1),s[1]!='E')    {        tt++;        len=strlen(s+1);        tot=0;        ch[++tot]='!';        ch[++tot]='#';        for(int i=1;i<=len;i++)        {            ch[++tot]=s[i];            ch[++tot]='#';        }         ch[++tot]='?';        manacher();        printf("Case %d: %d\n",tt,ans-1);    }} 
0 0