题目链接http://acm.hdu.edu.cn/showproblem.php?pid=6599
题意
给出一个字符串,统计有长度为1~n好串的个数。
好串的定义为:本身是回文串,左半边也是回文串。
题解
先用回文树跑一遍,对于每个本质不同的回文串进行判断,累加答案即可。至于判断,可以用马拉车等方法。但观察一下也可以发现,如果当前串长
t
1
t1
t1,和最长后缀回文串长
t
2
t2
t2满足关系:
(
t
1
/
2
)
%
(
t
1
−
t
2
)
=
=
0
(t1/2)\%(t1-t2)==0
(t1/2)%(t1−t2)==0,该串就是好串。
参考大佬博客:https://www.cnblogs.com/Chen-Jr/p/11240112.html
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=3e5+7;
struct PAM{//回文树
int nxt[N][26],fail[N],len[N],cnt[N],str[N];
int tot,n,lst;
int newnode(int x){
for(int i=0;i<26;i++) nxt[tot][i]=0;
cnt[tot]=0;
len[tot]=x;
return tot++;
}
void init(){
tot=lst=n=0;
newnode(0);
newnode(-1);
fail[0]=1;
str[0]=-1;
}
int getfail(int x){
while(str[n-len[x]-1]!=str[n]) x=fail[x];
return x;
}
void ist(int c){
str[++n]=c;
int cur=getfail(lst);
if(!nxt[cur][c]){
int now=newnode(len[cur]+2);
fail[now]=nxt[getfail(fail[cur])][c];
nxt[cur][c]=now;
}
lst=nxt[cur][c];
cnt[lst]++;
}
void getsum(){
for(int i=tot-1;i>=0;i--){
cnt[fail[i]]+=cnt[i];
}
}
}pam;
char s[N];
int ans[N];
bool ck(int x){
int t1=pam.len[x];
int t2=pam.len[pam.fail[x]];
return ((t1/2)%(t1-t2))==0;
}
int main(){
while(scanf("%s",s)!=EOF){
pam.init();
int sz=strlen(s);
for(int i=0;i<sz;i++){
pam.ist(s[i]-'a');
ans[i+1]=0;
}
pam.getsum();
for(int i=0;i<pam.tot;i++){
if(ck(i)) ans[pam.len[i]]+=pam.cnt[i];
}
for(int i=1;i<=sz;i++){
printf("%d%c",ans[i],i==sz?'\n':' ');
}
}
}