-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSuffixArray.cpp
More file actions
29 lines (28 loc) · 909 Bytes
/
SuffixArray.cpp
File metadata and controls
29 lines (28 loc) · 909 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
int sa[maxl], pos[maxl], tmp[maxl], lcp[maxl];
void buildSA(string s) {
int n = s.size();
for (int i = 0; i < n; i++)
sa[i] = i, pos[i] = s[i];
for (int gap = 1;; gap *= 2) {
auto sufCmp = [&n, &gap](int i, int j) {
if (pos[i] != pos[j])
return pos[i] < pos[j];
i += gap;
j += gap;
return (i < n && j < n) ? pos[i] < pos[j] : i > j;
};
sort(sa, sa + n, sufCmp);
for (int i = 0; i < n - 1; i++)
tmp[i + 1] = tmp[i] + sufCmp(sa[i], sa[i + 1]);
for (int i = 0; i < n; i++)
pos[sa[i]] = tmp[i];
if (tmp[n - 1] == n - 1) break;
}
for (int i = 0, k = 0; i < n; ++i)
if (pos[i] != n - 1) {
for (int j = sa[pos[i] + 1]; s[i + k] == s[j + k];)
++k;
lcp[pos[i] + 1] = k;
if (k)--k;
}
}