A string is finite sequence of characters over a non-empty finite set
Σ.In this problem, Σ is the set of lowercase letters.
Substring, also called factor, is a consecutive sequence of characters
occurrences at least once in a string.Now your task is a bit harder, for some given strings, find the length
of the longest common substring of them.Here common substring means a substring of two or more strings. Input
The input contains at most 10 lines, each line consists of no more
than 100000 lowercase letters, representing a string. OutputThe length of the longest common substring. If such string doesn’t
exist, print “0” instead.
把第一个串建出后缀自动机,然后把后面每个串放上去匹配,每一次记录每个节点匹配的最大长度。
注意如果在自动机上走,需要记录当前匹配的长度。但是如果往fa走了一步,因为已经舍弃掉了一些字符,所以直接取到max。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int oo=0x3f3f3f3f;
char s[200010];
int fa[200010],son[200010][30],val[200010],
mxl[200010],cnt[200010],a[200010],ans[200010],n,m,tot=1;
void init()
{
int last=1,p,q,np,nq,x;
scanf("%s",s+1);
n=strlen(s+1);
for (int i=1;i<=n;i++)
{
x=s[i]-'a'+1;
p=last;
val[np=++tot]=val[p]+1;
while (p&&!son[p][x])
{
son[p][x]=np;
p=fa[p];
}
if (!p) fa[np]=1;
else
{
q=son[p][x];
if (val[p]+1==val[q]) fa[np]=q;
else
{
val[nq=++tot]=val[p]+1;
for (int j=1;j<=26;j++) son[nq][j]=son[q][j];
fa[nq]=fa[q];
fa[q]=fa[np]=nq;
while (p&&son[p][x]==q)
{
son[p][x]=nq;
p=fa[p];
}
}
}
last=np;
}
for (int i=1;i<=tot;i++)
{
ans[i]=val[i];
cnt[val[i]]++;
}
for (int i=1;i<=n;i++) cnt[i]+=cnt[i-1];
for (int i=1;i<=tot;i++) a[cnt[val[i]]--]=i;
}
void upd()
{
int p=1,now=0,x;
for (int i=1;i<=tot;i++) mxl[i]=0;
n=strlen(s+1);
for (int i=1;i<=n;i++)
{
x=s[i]-'a'+1;
if (son[p][x])
{
now++;
p=son[p][x];
}
else
{
while (p&&!son[p][x]) p=fa[p];
if (!p)
{
now=0;
p=1;
}
else
{
now=val[p]+1;
p=son[p][x];
}
}
mxl[p]=max(mxl[p],now);
}
for (int i=tot;i;i--)
{
if (fa[a[i]]&&mxl[a[i]]) mxl[fa[a[i]]]=val[fa[a[i]]];
ans[a[i]]=min(ans[a[i]],mxl[a[i]]);
}
}
void solve()
{
int ret=0;
for (int i=1;i<=tot;i++) ret=max(ret,ans[i]);
printf("%d\n",ret);
}
int main()
{
init();
while (scanf("%s",s+1)==1) upd();
solve();
}