Skip to content

Instantly share code, notes, and snippets.

@lazycal
Created April 24, 2014 07:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lazycal/11245721 to your computer and use it in GitHub Desktop.
Save lazycal/11245721 to your computer and use it in GitHub Desktop.
SPOJ-LCS2 sam
#include <cstdio>
#include <cstring>
#include <algorithm>
const int N = 100000 * 2 + 9;
char s[N];
struct SAM
{
int l[N],fa[N],ch[N][26],cnt,len,last,b[N],t[N],mnl[N],cl[N];
void init()
{
cnt = last = 1; len = 0;
memset(ch[1],0,sizeof ch[1]);
}
void add(int c)
{
int np = ++cnt,p = last; last = np;
l[np] = ++len; memset(ch[np],0,sizeof ch[np]);
for (; p && !ch[p][c]; p = fa[p]) ch[p][c] = np;
if (!p) fa[np] = 1;
else {
int q = ch[p][c];
if (l[p] + 1 == l[q]) fa[np] = q;
else {
int nq = ++cnt;
l[nq] = l[p] + 1;
memcpy(ch[nq],ch[q],sizeof ch[q]);
fa[nq] = fa[q];
fa[q] = fa[np] = nq;
for (; ch[p][c] == q; p = fa[p]) ch[p][c] = nq;
}
}
}
void build()
{
scanf("%s",s);
init();
for (char *c = s; *c; ++c) add(*c - 'a');
for (int i = 1; i <= len; ++i) b[i] = 0;
for (int i = 1; i <= cnt; ++i) ++b[l[i]];
for (int i = 1; i <= len; ++i) b[i] += b[i - 1];
for (int i = 1; i <= cnt; ++i) t[b[l[i]]--] = i;
for (int i = 1; i <= cnt; ++i) mnl[i] = l[i];
}
void solve()
{
while (~scanf("%s",s)) {
for (int i = 1; i <= cnt; ++i) cl[i] = 0;
int p = 1;
for (char *cc = s; *cc; ++cc) {
int c = *cc - 'a';
while (p && !ch[p][c]) p = fa[p];
if (!p) len = 0,p = 1;
else {
if (len > l[p]) len = l[p]; ++len;
p = ch[p][c];
}
if (cl[p] < len) cl[p] = len;
}
for (int j = cnt; j; --j) {
int i = t[j];
if (mnl[i] > cl[i]) mnl[i] = cl[i];
if (cl[i] && fa[i]) cl[fa[i]] = l[fa[i]];
}
}
int res = 0;
for (int i = 1; i <= cnt; ++i)
res = std::max(mnl[i],res);
printf("%d\n",res);
}
}sam;
int main()
{
#ifndef ONLINE_JUDGE
freopen("LCS2.in","r",stdin);
freopen("LCS2.out","w",stdout);
#endif
sam.build();
sam.solve();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment