题面

大秦为你打开题目传送门

题目描述

给定两个字符串,请找出它们的最长公共子串。

思路

由于本人不会后缀数组,所以我们就哈希淼过罢。

直接大力二分哈希找长度,搞定。

代码

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#pragma GCC optimize(2)
#pragma GCC optimize(3, "Ofast", "inline")
#include<bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef __int128 int128;
typedef unsigned long long ull;

namespace FastIO
{
// char buf[1 << 20], *p1, *p2;
// #define getchar() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1 << 20, stdin), p1 == p2) ? EOF : *p1++)
template<typename T> inline T read(T& x) {
x = 0;
int f = 1;
char ch;
while (!isdigit(ch = getchar())) if (ch == '-') f = -1;
while (isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar();
x *= f;
return x;
}
template<typename T, typename... Args> inline void read(T& x, Args &...x_) {
read(x);
read(x_...);
return;
}
inline ll read() {
ll x;
read(x);
return x;
}
};
using namespace FastIO;

const int N = 1e5 + 10;
const int B = 31;

char s[N], t[N];
int ls, lt;

ull Power[N];
ull hshS[N], hshT[N];
inline ull Hash(ull* a, int l, int r) { return a[r] - a[l - 1] * Power[r - l + 1]; }

inline void Input() {
scanf("%s%s", s + 1, t + 1);
}

inline void Init() {
ls = strlen(s + 1);
lt = strlen(t + 1);
Power[0] = 1;
for(int i = 1; s[i]; i++) {
hshS[i] = hshS[i - 1] * B + (s[i] - 'a');
Power[i] = Power[i - 1] * B;
}
for(int i = 1; t[i]; i++) {
hshT[i] = hshT[i - 1] * B + (t[i] - 'a');
Power[i] = Power[i - 1] * B;
}
}

inline bool Check(int len) {
vector<ull >v;
for(int i = 1; i + len - 1 <= ls; i++) {
v.push_back(Hash(hshS, i, i + len - 1));
}
sort(v.begin(), v.end());
for(int i = 1; i + len - 1 <= lt; i++) {
int pos = lower_bound(v.begin(), v.end(), Hash(hshT, i, i + len - 1)) - v.begin();
if(v[pos] == Hash(hshT, i, i + len - 1)) {
return true;
}
}
return false;
}

inline void Work() {
Init();
int l = 0, r = min(ls, lt), best = -1;
while(l <= r) {
int mid = (l + r) >> 1;
if(Check(mid)) { // This len is right
l = mid + 1;
best = mid;
}
else {
r = mid - 1;
}
}
printf("%d", best);
}

int main() {
int T = 1;
while(T--) {
Input();
Work();
}
return 0;
}