【SPOJ】Longest Common Substring(后缀自动机)

【SPOJ】Longest Common Substring(后缀自动机)

题面

Vjudge
题意:求两个串的最长公共子串

题解

\(SA\)的做法很简单
不再赘述

对于一个串构建\(SAM\)
另外一个串在\(SAM\)上不断匹配
最后计算答案就好了
匹配方法:
如果\(trans(s,c)\)存在
直接沿着\(trans\)走就行,同时\(cnt++\)
否则沿着\(parent\)往上跳
如果存在\(trans(now,c),cnt=now.longest+1\)
否则,如果不存在可行的\(now\)
\(now=1\)也就是空串所在的节点,\(cnt=0\)

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<set>
#include<map>
#include<vector>
#include<queue>
using namespace std;
#define MAX 255000
struct Node
{
    int son[26];
    int ff,len;
}t[MAX<<1];
int last=1,tot=1;
char ch[MAX];
int ans;
void extend(int c)
{
    int p=last,np=++tot;last=np;
    t[np].len=t[p].len+1;
    while(p&&!t[p].son[c])t[p].son[c]=np,p=t[p].ff;
    if(!p)t[np].ff=1;
    else
    {
        int q=t[p].son[c];
        if(t[q].len==t[p].len+1)t[np].ff=q;
        else
        {
            int nq=++tot;
            t[nq]=t[q];t[nq].len=t[p].len+1;
            t[q].ff=t[np].ff=nq;
            while(p&&t[p].son[c]==q)t[p].son[c]=nq;
        }
    }
}
int main()
{
    scanf("%s",ch+1);
    for(int i=1,l=strlen(ch+1);i<=l;++i)extend(ch[i]-97);
    scanf("%s",ch+1);
    for(int i=1,l=strlen(ch+1),now=1,tt=0;i<=l;++i)
    {
        if(t[now].son[ch[i]-97])
            ++tt,now=t[now].son[ch[i]-97];
        else
        {
            while(now&&!t[now].son[ch[i]-97])now=t[now].ff;
            if(!now)tt=0,now=1;
            else tt=t[now].len+1,now=t[now].son[ch[i]-97];
        }
        ans=max(ans,tt);
    }
    printf("%d\n",ans);
    return 0;
}

posted @ 2018-02-13 11:44  小蒟蒻yyb  阅读(317)  评论(0编辑  收藏  举报