Blog of RuSun

\begin {array}{c} \mathfrak {One Problem Is Difficult} \\\\ \mathfrak {Because You Don't Know} \\\\ \mathfrak {Why It Is Diffucult} \end {array}

SP1811 LCS - Longest Common Substring

LuoGu: SP1811 LCS - Longest Common Substring

用第一个串建立SAM,用第二个串在 SAM 上匹配,更新答案即可。

查看代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
template <class Type>
void read(Type &x)
{
char c;
bool flag = false;
while ((c = getchar()) < '0' || c > '9')
c == '-' && (flag = true);
x = c - '0';
while ((c = getchar()) >= '0' && c <= '9')
x = (x << 3) + (x << 1) + c - '0';
if (flag) x = ~x + 1;
}
template <class Type, class ...rest>
void read(Type &x, rest &...y) { read(x), read(y...); }
template <class Type>
void write(Type x)
{
if (x < 0) putchar('-'), x = ~x + 1;
if (x > 9) write(x / 10);
putchar(x % 10 + '0');
}
const int N = 5e5 + 10;
struct Node { int len, fa, nxt[26]; } tr[N];
char str[N];
int n, ans, last = 1, cnt = 1;
void insert(int c)
{
int p = last, np = ++cnt;
tr[np].len = tr[p].len + 1;
for (; p && !tr[p].nxt[c]; p = tr[p].fa) tr[p].nxt[c] = np;
last = np;
if (!p) return void(tr[np].fa = 1);
int q = tr[p].nxt[c];
if (tr[q].len == tr[p].len + 1) return void(tr[np].fa = q);
int nq = ++cnt;
tr[nq] = tr[q], tr[nq].len = tr[p].len + 1;
tr[q].fa = tr[np].fa = nq;
for (; p && tr[p].nxt[c] == q; p = tr[p].fa) tr[p].nxt[c] = nq;
}
int main()
{
scanf("%s", str + 1);
n = strlen(str + 1);
for (int i = 1; i <= n; i++) insert(str[i] - 'a');
scanf("%s", str + 1);
n = strlen(str + 1);
for (int i = 1, p = 1, t = 0; i <= n; ++i)
{
int c = str[i] - 'a';
while (p && !tr[p].nxt[c]) p = tr[p].fa, t = tr[p].len;
if (tr[p].nxt[c]) p = tr[p].nxt[c], ++t;
else p = 1, t = 0;
if (t > ans) ans = t;
}
write(ans);
return 0;
}