SPOJ1811 LCS - Longest Common Substring(后缀自动机)

时间:2022-09-30 20:34:31

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.

Input

The input contains exactly two lines, each line consists of no more than 250000 lowercase letters, representing a string.

Output

The length of the longest common substring. If such string doesn't exist, print "0" instead.

Example

Input:
alsdfkjfjkdsal
fdjskalajfkdsla Output:
3

Notice: new testcases added

为什么都说这是后缀自动机的裸题啊。难道就我看不出来么qwq、、

正解其实比较好想,先把第一个串扔到SAM里面

对于第二个串依次枚举,如果能匹配就匹配,否则就沿着parent边走(怎么这么像AC自动机??),顺便记录一下最长长度

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAXN = * + ;
char s1[MAXN], s2[MAXN];
int N1, N2, tot = , root = , last = , len[MAXN], ch[MAXN][], fa[MAXN];
void insert(int x) {
int now = ++tot, pre = last; last = now; len[now] = len[pre] + ;
for(; pre && !ch[pre][x]; pre = fa[pre]) ch[pre][x] = now;
if(!pre) fa[now] = root;
else {
int q = ch[pre][x];
if(len[q] == len[pre] + ) fa[now] = q;
else {
int nows = ++tot;
memcpy(ch[nows], ch[q], sizeof(ch[q]));
len[nows] = len[pre] + ;
fa[nows] = fa[q]; fa[now] = fa[q] = nows;
for(; pre && ch[pre][x] == q; pre = fa[pre]) ch[pre][x] = nows;
}
} }
int main() {
#ifdef WIN32
freopen("a.in", "r", stdin);
#endif
scanf("%s %s", s1 + , s2 + );
N1 = strlen(s1 + );
N2 = strlen(s2 + );
for(int i = ; i <= N1; i++)
insert(s1[i] - 'a');
int ans = , nowlen = , cur = root;
for(int i = ; i <= N2; i++, ans = max(ans, nowlen)) {
int p = s2[i] - 'a';
if(ch[cur][p]) {nowlen++, cur = ch[cur][p]; continue;}
for(; cur && !ch[cur][p]; cur = fa[cur]);
nowlen = len[cur] + , cur = ch[cur][p];
}
printf("%d\n", ans);
return ;
}