spoj LCS
初识后缀自动机;
推荐学习:http://blog.sina.com.cn/s/blog_7812e98601012dfv.html
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 #define maxn 600009 5 using namespace std; 6 7 char s[maxn]; 8 9 struct node 10 { 11 int l; 12 node *ch[28],*fail; 13 } pool[maxn],*head,*tail; 14 int top; 15 void add(int x) 16 { 17 node *p=&pool[++top],*bj=tail; 18 p->l=tail->l+1; 19 tail=p; 20 for(; bj&&!bj->ch[x]; bj=bj->fail) 21 bj->ch[x]=p; 22 if(!bj)p->fail=head; 23 else if(bj->l+1==bj->ch[x]->l)p->fail=bj->ch[x]; 24 else 25 { 26 node *r=&pool[++top],*q=bj->ch[x]; 27 *r=*q; 28 r->l=bj->l+1; 29 p->fail=q->fail=r; 30 for(; bj&&bj->ch[x]==q; bj=bj->fail)bj->ch[x]=r; 31 } 32 } 33 34 int main() 35 { 36 scanf("%s",s); 37 int n=strlen(s); 38 head=tail=&pool[++top]; 39 for(int i=0; i<n; i++) 40 add(s[i]-'a'+1); 41 scanf("%s",s); 42 n=strlen(s); 43 tail=head; 44 int mid=0,ans=0; 45 for(int i=0; i<n; i++) 46 { 47 if(tail->ch[s[i]=s[i]-'a'+1]) 48 { 49 ++mid; 50 tail=tail->ch[s[i]]; 51 } 52 else 53 { 54 while(tail&&!tail->ch[s[i]])tail=tail->fail; 55 if(!tail)tail=head,mid=0; 56 else 57 { 58 mid=tail->l+1; 59 tail=tail->ch[s[i]]; 60 } 61 } 62 ans=max(ans,mid); 63 } 64 printf("%d\n", ans); 65 return 0; 66 }