Loj141. 回文子串
Posted aaddvvaanntteezz
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Loj141. 回文子串相关的知识,希望对你有一定的参考价值。
题解
回文自动机双向插入模版题,还需要动态维护回文子串个数,贴个板子查看代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e6+5;
const int mod = 1e9+7;
ll qpow(ll a,ll b){ll res=1;for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}
struct PAM
{
char s[maxn];
int ch[maxn][26],fail[maxn],dep[maxn],lastf,lastb,tot,len[maxn],l,r;
ll ans;
PAM()
{
fail[0]=1;
len[1]=-1;
tot=1;
l = 5e5,r = 5e5-1;
}
void push_back(char c){
s[++r]=c;
int p = c-‘a‘;
int q = lastb;
while(s[r-len[q]-1]!=c){
q = fail[q];
}
if(!ch[q][p]){
len[++tot]=len[q]+2;
int f = fail[q];
while(s[r-len[f]-1]!=c)f = fail[f];
fail[tot]=ch[f][p];
ch[q][p]=tot;
dep[tot]=dep[fail[tot]]+1;
}
lastb = ch[q][p];
if(len[lastb]==r-l+1)lastf=lastb;
ans+=dep[lastb];
}
void push_front(char c){
s[--l]=c;
int p = c-‘a‘;
int q = lastf;
while(s[l+len[q]+1]!=c)q = fail[q];
if(!ch[q][p]){
len[++tot]=len[q]+2;
ch[q][p]=tot;
int f = fail[q];
while(s[l+len[f]+1]!=c)f = fail[f];
fail[tot]=ch[f][p];
dep[tot]=dep[fail[tot]]+1;
}
lastf = ch[q][p];
if(len[lastf]==r-l+1)lastb=lastf;
ans+=dep[lastf];
}
}pam;
char s[maxn];
int main()
{
scanf("%s",s+1);
for(int i = 1;s[i];++i)pam.push_back(s[i]);
int q;
scanf("%d",&q);
int opt;
while(q--){
scanf("%d",&opt);
if(opt==1){
scanf("%s",s+1);
for(int i = 1;s[i];++i)pam.push_back(s[i]);
}
else if(opt==2){
scanf("%s",s+1);
for(int i = 1;s[i];++i)pam.push_front(s[i]);
}
else printf("%lld
",pam.ans);
}
return 0;
}
以上是关于Loj141. 回文子串的主要内容,如果未能解决你的问题,请参考以下文章