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.
Output
The length of the longest common substring. If such string doesn't exist, print "0" instead.
Example
Input:
alsdfkjfjkdsal
fdjskalajfkdsla
aaaajfaaaa Output:
2
題解:
這題走了許多彎路,最後好不容易拍完錯誤,代碼沒有改得精簡.
思路可以參考:
根據上題可以想到,拿每一個串都在A得SAM上跑,然後記錄當前串在SAM得每一個節點的最大值,然後如果是多個串的話
直接記錄最小值即可,最後掃一邊記錄最小值的最大值即可
注意一些細節:
對於沒一個串的匹配,如果當前結點被匹配到了,那麼他的父親結點都可以匹配到,那麼直接拓撲序更新即可,不然就WA#10哦..
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#define il inline
#define RG register
using namespace std;
const int N=;
char s[N];int cur=,cnt=,last=,fa[N],ch[N][],dis[N],n=;
void build(int c)
{
last=cur;cur=++cnt;
RG int p=last;dis[cur]=++n;
for(;p && !ch[p][c];p=fa[p])ch[p][c]=cur;
if(!p)fa[cur]=;
else{
int q=ch[p][c];
if(dis[q]==dis[p]+)fa[cur]=q;
else{
int nt=++cnt;dis[nt]=dis[p]+;
memcpy(ch[nt],ch[q],sizeof(ch[q]));
fa[nt]=fa[q];fa[q]=fa[cur]=nt;
for(;ch[p][c]==q;p=fa[p])ch[p][c]=nt;
}
}
}
int id=,t[N],tot[N],mx[N],sa[N];bool mark[N][];
void FLr()
{
RG int p=,l=strlen(s),c,u,len=;id++;
for(RG int i=;i<l;i++){
c=s[i]-'a';
u=ch[p][c];
if(u){
mark[u][id]=true;len++;
p=u;
}
else{
while(p && !ch[p][c])p=fa[p];
if(p){
mark[ch[p][c]][id]=true;
len=dis[p]+;
p=ch[p][c];
}
else p=,len=;
}
if(len>mx[p])mx[p]=len;
}
for(RG int i=cnt;i;i--){
p=sa[i];
if(mx[p]<tot[p])tot[p]=mx[p];
if(fa[p] && mark[p][id])mx[fa[p]]=dis[fa[p]];
mx[p]=;
}
}
int c[N];
void Dfp(){
RG int p,i,j;
for(i=cnt;i;i--){
p=sa[i];
for(j=;j<=id;j++)
mark[fa[p]][j]|=mark[p][j];
}
for(i=;i<=cnt;i++)
for(j=;j<=id;j++)
if(mark[i][j])t[i]++;
}
int ans=;
void dfs(){
for(int i=;i<=cnt;i++){
if(t[i] && tot[i]>ans)ans=tot[i];
}
}
void jip(){
RG int i;
for(i=;i<=cnt;i++)c[dis[i]]++;
for(i=;i<=n;i++)c[i]+=c[i-];
for(i=cnt;i;i--)sa[c[dis[i]]--]=i;
}
void work()
{
scanf("%s",s);
for(RG int i=,l=strlen(s);i<l;i++)build(s[i]-'a');
for(RG int i=;i<=cnt;i++)tot[i]=N;
jip();
while(~scanf("%s",s))FLr();
Dfp();dfs();
printf("%d\n",ans);
}
int main()
{
freopen("pow.in","r",stdin);
freopen("pow.out","w",stdout);
work();
return ;
}