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

后缀自动机 模版

时间:2016-05-04 01:24:05      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
#include<bits/stdc++.h>
#define REP(i,a,b) for(int i=a;i<=b;i++)
#define MS0(a) memset(a,0,sizeof(a))

using namespace std;

typedef long long ll;
const int maxn=2000100;
const int INF=1e9+10;

struct SAM
{
    int ch[maxn][26];
    int pre[maxn],step[maxn];
    int last,tot;
    void init()
    {
        last=tot=0;
        memset(ch[0],-1,sizeof(ch[0]));
        pre[0]=-1;
        step[0]=0;
    }
    void add(int c)
    {
        c-=a;
        int p=last,np=++tot;
        step[np]=step[p]+1;
        memset(ch[np],-1,sizeof(ch[np]));
        while(~p&&ch[p][c]==-1) ch[p][c]=np,p=pre[p];
        if(p==-1) pre[np]=0;
        else{
            int q=ch[p][c];
            if(step[q]!=step[p]+1){
                int nq=++tot;
                step[nq]=step[p]+1;
                memcpy(ch[nq],ch[q],sizeof(ch[q]));
                pre[nq]=pre[q];
                pre[q]=pre[np]=nq;
                while(~p&&ch[p][c]==q) ch[p][c]=nq,p=pre[p];
            }
            else pre[np]=q;
        }
        last=np;
    }
    int find(char *s)
    {
        int len=strlen(s);
        int res=0,tmp=0;
        int u=0;
        REP(i,0,len-1){
            int c=s[i]-a;
            if(~ch[u][c]) tmp++,u=ch[u][c];
            else{
                while(~u&&ch[u][c]==-1) u=pre[u];
                if(~u) tmp=step[u]+1,u=ch[u][c];
                else tmp=0,u=0;
            }
            res=max(res,tmp);
        }
        return res;
    }
};SAM sam;
char s[maxn],t[maxn];

void solve()
{
    sam.init();
    int len=strlen(s);
    REP(i,0,len-1) sam.add(s[i]);
    printf("%d\n",sam.find(t));
}

int main()
{
    freopen("in.txt","r",stdin);
    while(~scanf("%s%s",s,t)){
        solve();
    }
    return 0;
}
View Code

调了挺久,就用spoj1811的代码做模版吧。。。

 

后缀自动机 模版

标签:

原文地址:http://www.cnblogs.com/--560/p/5457025.html

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