题解
这题一眼建双端回文自动机。
可是怎么建啊…这个操作十分巧妙,感觉要真正理解回文自动机才行。
先把字符串大小开到两倍,每次插入处理在中端点的位置,同时pos[0/1]记一下字符串位于两端的位置。
但这是回文自动机,性质十分特殊。自动机上的每个节点对应一个回文子串,那么其实前端和后端的加入处理起来并不麻烦,可以在同一自动机上处理。
前端的last指向的即字符串最长回文前缀,后端的last指向的即字符串最长回文后缀。
当最长回文前/后缀覆盖了整个串的时候,我们就可以把两个last合并到同一个节点上。
那么针对1,2操作就没有问题了。
本质不同的回文子串,就是回文自动机上的节点数-2(除去节点0和节点1)
对于所有不同的回文子串,可以考虑为:每加入一个字符,更新了最大回文前缀/后缀后,新产生的回文子串个数,即为回文自动机上该节点的深度。
代码
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+100;
typedef long long ll;
int T,op,n,cnt,tot,p[2],pos[2];
int s[N<<1],dep[N<<1],len[N<<1],ch[N<<1][26],f[N<<1];
char c[5];
ll ans;
inline int new_node(int m)
{
memset(ch[cnt],0,sizeof(ch[cnt]));
len[cnt]=m;dep[cnt]=0;return cnt++;
}
inline void itia()
{
cnt=0;f[0]=1;ans=0;
new_node(0);new_node(-1);
p[0]=p[1]=0;pos[0]=N;pos[1]=N-1;
}
inline int get_fail(int x,int sta)
{
s[pos[0]-1]=s[pos[1]+1]=-1;
for(;s[pos[sta]+(sta?(-1-len[x]):(1+len[x]))]!=s[pos[sta]];)
x=f[x];
return x;
}
inline void ad(int alp,int sta)
{
pos[sta]+=(sta?1:-1);
s[pos[sta]]=alp;
p[sta]=get_fail(p[sta],sta);
if(!ch[p[sta]][alp]){
int now=new_node(len[p[sta]]+2);
f[now]=ch[get_fail(f[p[sta]],sta)][alp];
ch[p[sta]][alp]=now;
dep[now]=dep[f[now]]+1;
p[sta]=now;
if(len[now]==pos[1]-pos[0]+1) p[sta^1]=p[sta];
}
else p[sta]=ch[p[sta]][alp];
ans+=dep[p[sta]];
}
int main(){
while(scanf("%d",&T)==1){
itia();
for(;T;--T){
scanf("%d",&op);
if(op<3){
scanf("%s",c);ad(c[0]-'a',op-1);
}else{
if(op==3) printf("%d\n",cnt-2);
else printf("%lld\n",ans);
}
}
}
}