浅谈 Manacher

基本概念

回文子串:字符串中反转后与反转前相同的子串。

最长回文子串:字符串中长度最大的回文子串。

第 $i$ 位回文半径:以字符串第 $i$ 位为中心的回文子串的最大长度的一半。

在处理回文子串的问题时,一般需要求出字符串每一位的回文半径。

为了避免奇偶讨论和边界问题,我们可以在每一位字符两侧添加同一个特殊字符,在字符串的首尾各添加一个不同的特殊字符,如将 abbabcba 变为 $#a#b#b#a#b#c#b#a#@

Manacher 算法流程

在 Manacher 算法中,我们需要添加两个辅助变量 $mx$ 和 $p$,分别表示已有的回文半径覆盖到的最右边界(边界不含)和该回文子串的中心位置,显然有 $mx=p+R[p]$。($R_i$ 表示第 $i$ 位的回文半径)

计算 $R_i$ 时,我们可以先给它定一个下界,这样可以节省时间复杂度。

令 $j=2p-i$,分以下三种情况讨论:

  1. $mx\leq i$,向右覆盖最远的回文串没有覆盖到 $i$ 位置,而因为恒有 $R_i\ge 1$,所以 $R_i$ 的下界为 $1$。
  2. $mx-i>R_j$,以第 $j$ 位为中心的回文子串包含于以第 $p$ 位为中心的回文子串,由于 $i$ 和 $j$ 关于 $p$ 对称,那么以第 $i$ 位为中心的回文子串必也包含于以第 $p$ 位为中心的回文子串,故有 $R_i=R_j$。
  3. $mx-i\leq R_j$,以第 $j$ 位为中心的回文子串不一定包含于以第 $p$ 位为中心的回文子串,但由对称可知,$R_i\ge mx-i$。

Snipaste_2021-02-27_20-57-23

Code

例题:不交回文串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include<bits/stdc++.h>
#define Tp template<typename Ty>
#define Ts template<typename Ty,typename... Ar>
#define W while
#define I inline
#define RI register int
#define LL long long
#define Cn const
#define CI Cn int&
#define gc getchar
#define D isdigit(c=gc())
#define pc(c) putchar((c))
#define min(x,y) ((x)<(y)?(x):(y))
#define max(x,y) ((x)>(y)?(x):(y))
using namespace std;
namespace Debug{
Tp I void _debug(Cn char* f,Ty t){cerr<<f<<'='<<t<<endl;}
Ts I void _debug(Cn char* f,Ty x,Ar... y){W(*f!=',') cerr<<*f++;cerr<<'='<<x<<",";_debug(f+1,y...);}
Tp ostream& operator<<(ostream& os,Cn vector<Ty>& V){os<<"[";for(Cn auto& vv:V) os<<vv<<",";os<<"]";return os;}
#define gdb(...) _debug(#__VA_ARGS__,__VA_ARGS__)
}using namespace Debug;
namespace FastIO{
Tp I void read(Ty& x){char c;int f=1;x=0;W(!D) f=c^'-'?1:-1;W(x=(x<<3)+(x<<1)+(c&15),D);x*=f;}
Ts I void read(Ty& x,Ar&... y){read(x),read(y...);}
Tp I void write(Ty x){x<0&&(pc('-'),x=-x,0),x<10?(pc(x+'0'),0):(write(x/10),pc(x%10+'0'),0);}
Tp I void writeln(Cn Ty& x){write(x),pc('\n');}
}using namespace FastIO;
Cn int N=1e5+10;
char s[N<<1],str[N];
LL pre[N<<1],suf[N<<1],sum[N<<1];
int len,p[N<<2],L;
I void init(){
RI i;for(s[0]='$',s[1]='#',L=2,i=0;i<len;i++) s[L++]=str[i],s[L++]='#';s[L]='\0';
}
I void Manacher(){
RI mx=0,id=0,i;for(init(),i=1;i<L;i++){
if(i<mx) p[i]=min(p[2*id-i],mx-i);
else p[i]=1;
// p[i]=min(mx-i,p[id*2-i]);
W(s[i-p[i]]==s[i+p[i]]) p[i]++;
if(mx<i+p[i]) id=i,mx=i+p[i];
}
}
int main(){
RI i;W(~scanf("%s",&str)){
len=strlen(str);for(i=0;i<=len;i++) suf[i]=pre[i]=sum[i]=0;
for(Manacher(),i=2;i<=len*2;i++) suf[(i+1)/2]++,suf[(i+1)/2+p[i]/2]--;
for(i=len*2;i>=2;i--) pre[i/2]++,pre[i/2-p[i]/2]--;
for(i=len;i>=1;i--) pre[i]+=pre[i+1];
for(i=1;i<=len;i++) suf[i]+=suf[i-1],sum[i]=sum[i-1]+suf[i];
LL Ans=0;for(i=1;i<=len;i++) Ans+=(LL)pre[i]*sum[i-1];
writeln(Ans);
}return 0;
}