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

【模板】后缀自动机

时间:2018-12-10 11:35:18      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:%s   strlen   i++   int   algo   代码   names   main   pac   

模板题,这里放一下代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define N 1000050
#define ll long long
char s[N];
ll ans = 0;
struct SAM
{
    int tot,las;
    int siz[2*N];
    SAM(){tot=las=1;}
    struct Poi
    {
        int pre,trs[28],len;
    }p[2*N];
    struct EG
    {
        int to,nxt;
    }e[2*N];
    int hed[2*N],cnt;
    void ae(int f,int t)
    {
        e[++cnt].to = t;
        e[cnt].nxt = hed[f];
        hed[f] = cnt;
    }
    void insert(int c)
    {
        int np,nq,lp,lq;
        np=++tot;
        siz[np]=1;
        p[np].len=p[las].len+1;
        for(lp=las;lp&&!p[lp].trs[c];lp=p[lp].pre)
            p[lp].trs[c]=np;
        if(!lp)p[np].pre=1;
        else
        {
            lq = p[lp].trs[c];
            if(p[lq].len==p[lp].len+1)p[np].pre=lq;
            else
            {
                nq = ++tot;
                p[nq]=p[lq];
                p[nq].len=p[lp].len+1;
                p[lq].pre=p[np].pre=nq;
                while(p[lp].trs[c]==lq)
                {
                    p[lp].trs[c]=nq;
                    lp=p[lp].pre;
                }
            }
        }
        las=np;
    }
    void build()
    {
        for(int i=2;i<=tot;i++)
            ae(p[i].pre,i);
    }
    void dfs(int u)
    {
        for(int j=hed[u];j;j=e[j].nxt)dfs(e[j].to),siz[u]+=siz[e[j].to];
        if(siz[u]!=1)ans=max(1ll*siz[u]*p[u].len,ans);
    }
}sam;
int len;
int main()
{
    scanf("%s",s+1);
    len = strlen(s+1);
    for(int i=1;i<=len;i++)
        sam.insert(s[i]-a+1);
    sam.build();
    sam.dfs(1);
    printf("%lld\n",ans);
    return 0;
}

 

【模板】后缀自动机

标签:%s   strlen   i++   int   algo   代码   names   main   pac   

原文地址:https://www.cnblogs.com/LiGuanlin1124/p/10094807.html

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