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.
The input contains at most 10 lines, each line consists of no more than 100000 lowercase letters, representing a string.
The length of the longest common substring. If such string doesn't exist, print "0" instead.
Input: alsdfkjfjkdsal fdjskalajfkdsla aaaajfaaaa Output: 2
第一个串建SAM,剩下的串在上面跑....记录下每个节点的最小匹配长度(初始值是 len 即能表示的最长后缀),
从后向前更新fa节点的LCS....
#include<iostream> #include<cstring> #include<cstdio> #include<queue> using namespace std; #define ll long long #define prt(k) cout<<#k"="<<k<<" "; /**Suffix Automaton*/ const int Char=26,N=1000022; struct SAM_Node { SAM_Node *fa,*ch[Char]; int len,id,pos; SAM_Node() {} SAM_Node(int _len) { fa=0; len=_len; memset(ch,0,sizeof ch); } }pool[N],*root,*last,*tail; ///tail int SAM_size; #define node SAM_Node SAM_Node *newnode(int len) { pool[SAM_size]=node(len); pool[SAM_size].id=SAM_size; return &pool[SAM_size++]; } node *newnode(node *p) { pool[SAM_size]=*p; pool[SAM_size].id=SAM_size; return &pool[SAM_size++]; } void SAM_init() { SAM_size=0; root=last=newnode(0); pool[0].pos=0; } void add(int x,int len) { node *p=last,*np=newnode(p->len+1); np->pos=len; last=np; for(;p&&!p->ch[x];p=p->fa) p->ch[x]=np; if(!p) { np->fa=root;return ; } node *q=p->ch[x]; if(q->len==p->len+1) { np->fa=q;return; } node *nq=newnode(q); nq->len=p->len+1; q->fa=nq; np->fa=nq; for(;p&&p->ch[x]==q;p=p->fa) p->ch[x]=nq; } void SAM_build(char *s) { SAM_init(); int len=strlen(s); for(int i=0;i<len;i++) add(s[i]-'a',i+1); } char a[N],b[N]; int c[N]; node *top[N]; int LCS[N]; void Max(int &a,int b) { a=max(a,b); } void Min(int &a,int b) { a=min(a,b); } int main() { scanf("%s",a); SAM_build(a); for(int i=0;i<SAM_size;i++) c[pool[i].len]++; for(int i=1;i<=SAM_size;i++) c[i]+=c[i-1]; for(int i=0;i<SAM_size;i++) top[--c[pool[i].len]]=&pool[i]; int ans=0; while(scanf("%s",b)==1) { int ans=0,tmp=0; node *u=root; for(int i=0;b[i];i++) { int c=b[i]-'a'; if(u->ch[c]) { u=u->ch[c]; tmp++; } else { while(u&&!u->ch[c]) u=u->fa; if(u) { tmp=u->len+1; u=u->ch[c]; } else { tmp=0; u=root; } } Max(LCS[u->id],tmp); } for(int i=SAM_size-1;i>=0;i--) { Min(top[i]->len,LCS[top[i]->id]); if(top[i]->fa) Max(LCS[top[i]->fa->id],LCS[top[i]->id]); LCS[top[i]->id]=0; } } ans=0; for(int i=0;i<SAM_size;i++) Max(ans,pool[i].len); cout<<ans<<endl; }