-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsuffix_array.cpp
More file actions
64 lines (55 loc) · 1.35 KB
/
suffix_array.cpp
File metadata and controls
64 lines (55 loc) · 1.35 KB
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
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// Suffix Array (O(Nlog^2N))
vector<int> getSuffixArray(const string &s) {
int n = s.size();
vector<int> sa(n), rank(n);
vector<int> new_rank(n);
for (int i = 0; i < n; i++) {
sa[i] = i;
rank[i] = s[i];
}
for (int d = 1; d < n; d *= 2) {
auto cmp = [&](int i, int j) {
if (rank[i] != rank[j])
return rank[i] < rank[j];
int ri = (i + d < n) ? rank[i + d] : -1;
int rj = (j + d < n) ? rank[j + d] : -1;
return ri < rj;
};
sort(sa.begin(), sa.end(), cmp);
new_rank[sa[0]] = 0;
for (int i = 1; i < n; i++) {
if (cmp(sa[i - 1], sa[i]))
new_rank[sa[i]] = new_rank[sa[i - 1]] + 1;
else
new_rank[sa[i]] = new_rank[sa[i - 1]];
}
rank = new_rank;
if (rank[sa[n - 1]] == n - 1)
break;
}
return sa;
}
// LCP Array (O(N)) - using Kasai's algorithm
vector<int> getLCP(const string &s, const vector<int> &sa) {
int n = s.size();
vector<int> rank(n), lcp(n);
for (int i = 0; i < n; i++)
rank[sa[i]] = i;
int h = 0;
for (int i = 0; i < n; i++) {
if (rank[i] > 0) {
int j = sa[rank[i] - 1];
while (i + h < n && j + h < n && s[i + h] == s[j + h])
h++;
lcp[rank[i]] = h;
if (h > 0)
h--;
}
}
return lcp;
}