码迷,mamicode.com
首页 > 其他好文 > 详细

Loj141. 回文子串

时间:2020-06-11 13:47:22      阅读:55      评论:0      收藏:0      [点我收藏+]

标签:插入   tps   last   模版题   back   int   mod   bit   pac   

题目链接

题解

回文自动机双向插入模版题,还需要动态维护回文子串个数,贴个板子
查看代码
#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\n",pam.ans);
    }
    return 0;
}

Loj141. 回文子串

标签:插入   tps   last   模版题   back   int   mod   bit   pac   

原文地址:https://www.cnblogs.com/aaddvvaanntteezz/p/13092550.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!