link/cut tree
[kudsource.git] / SPOJ / LCS.cc
bloba0fa9ec9689f3f251978c9f40e9c3ecf0dc14204
1 #include <cstdio>
2 #include <cstring>
3 #include <algorithm>
5 using namespace std;
7 const int maxn=250000+10;
9 struct SAM
11 int len;
12 SAM *pre,*next[26];
13 SAM(): pre(NULL), len(0) { memset(next,0,sizeof(next)); }
14 } sam[maxn*4],*root,*last;
16 int cnt=0;
18 namespace suffix_automation
20 void insert(int ch) //ch==ASCII code - 'a'
22 SAM *p=last,*np=&sam[cnt++];
23 np->len=last->len+1;
24 for (; p && !p->next[ch]; p=p->pre) p->next[ch]=np;
25 last=np;
26 if (!p) np->pre=root; else
27 if (p->next[ch]->len==p->len+1) np->pre=p->next[ch]; else
29 SAM *q=p->next[ch],*nq=&sam[cnt++];
30 *nq=*q;
31 nq->len=p->len+1;
32 q->pre=np->pre=nq;
33 for (; p && p->next[ch]==q; p=p->pre) p->next[ch]=nq;
37 int solve(char s[])
39 int n=strlen(s),res=0,tmp=0;
40 SAM *now=root;
41 for (int i=0; i<n; ++i)
43 int ch=s[i]-'a';
44 if (now->next[ch]) ++tmp,now=now->next[ch]; else
46 while (now && !now->next[ch]) now=now->pre;
47 if (!now) now=root,tmp=0; else tmp=now->len+1,now=now->next[ch];
49 res=max(res,tmp);
51 return res;
55 char a[maxn],b[maxn];
57 int main()
59 last=root=&sam[cnt++];
60 scanf("%s %s",a,b);
61 int n=strlen(a);
62 for (int i=0; i<n; ++i) suffix_automation::insert(a[i]-'a');
63 printf("%d\n",suffix_automation::solve(b));