模板(求最大回文串长度)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std
;
char s
[11000002];
char s_new
[21000002];
int p
[21000002];
int Init() {
int len
=strlen(s
);
s_new
[0]='$';
s_new
[1]='#';
int j
=2;
for(int i
=0;i
<len
;i
++) {
s_new
[j
++]=s
[i
];
s_new
[j
++]='#';
}
s_new
[j
]='\0';
return j
;
}
int Manacher() {
int len
=Init();
int max_len
=-1;
int id
;
int mx
=0;
for(int i
=1;i
<=len
;i
++) {
if(i
<mx
)
p
[i
]=min(p
[2*id
-i
],mx
-i
);
else p
[i
]=1;
while(s_new
[i
-p
[i
]]==s_new
[i
+p
[i
]])
p
[i
]++;
if(mx
<i
+p
[i
]) {
id
=i
;
mx
=i
+p
[i
];
}
max_len
=max(max_len
,p
[i
]-1);
}
return max_len
;
}
int main()
{
scanf("%s",&s
);
printf("%d",Manacher());
return 0;
}
思路
使原串中的偶回文(abba)与奇回文(adcacda),变成(#a#d#d#a#)与(#a#d#c#a#c#d#a#)两个奇回文。
类似于z算法 定义一个mx和id
转载请注明原文地址:https://blackberry.8miu.com/read-2028.html