-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkmp.cpp
More file actions
36 lines (36 loc) · 734 Bytes
/
Copy pathkmp.cpp
File metadata and controls
36 lines (36 loc) · 734 Bytes
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
// https://github.com/atcoder-live/library/blob/master/mp.cpp
//
// Morris-Pratt
// https://youtu.be/9MphwmIsO7Q?t=7283
template<typename T>
struct MP {
int n;
T t;
vector<int> a;
MP() {}
MP(const T& t): t(t) {
n = t.size();
a = vector<int>(n+1);
a[0] = -1;
int j = -1;
for (int i = 0; i < n; ++i) {
while (j != -1 && t[j] != t[i]) j = a[j];
j++;
a[i+1] = j;
}
}
int operator[](int i) { return a[i];}
vector<int> findAll(const T& s) {
vector<int> res;
int j = 0;
for (int i = 0; i < s.size(); ++i) {
while (j != -1 && t[j] != s[i]) j = a[j];
j++;
if (j == n) {
res.push_back(i-j+1);
j = a[j];
}
}
return res;
}
};