后缀自动机模板。。
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 simple, for two 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 exactly two lines, each line consists of no more than 250000 lowercase letters, representing a string.
The length of the longest common substring. If such string doesn't exist, print "0" instead.
Input: alsdfkjfjkdsal fdjskalajfkdsla Output: 3
Notice: new testcases added
#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 main() { while(scanf("%s%s",a,b)==2) { SAM_build(a); 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; } } ans=max(ans,tmp); } cout<<ans<<endl; } }