-
Notifications
You must be signed in to change notification settings - Fork 2
/
SuffixArray.cpp
68 lines (53 loc) · 1.47 KB
/
SuffixArray.cpp
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
class SuffixArray
{
public:
SuffixArray(const string& str)
{
constructSA(str);
constructLCP(str);
}
vector<int> sa;
vector<int> lcp;
private:
void constructSA(const string& str)
{
pos.resize(str.size());
sa.resize(str.size());
for (int i = 0; i < str.size(); i++)
{
sa[i] = i;
pos[i] = str[i];
}
for (int d = 1;; d *= 2)
{
sort(sa.begin(), sa.end(), [this, d](auto& l, auto& r) { return cmp(l, r, d); });
vector<int> temp(str.size());
for (int i = 0; i < str.size() - 1; i++)
temp[i + 1] = temp[i] + cmp(sa[i], sa[i + 1], d);
for (int i = 0; i < str.size(); i++)
pos[sa[i]] = temp[i];
if (temp[str.size() - 1] == str.size() - 1)
break;
}
}
void constructLCP(const string& str)
{
lcp.resize(str.size());
for (int i = 0, k = 0; i < str.size(); i++, k = max(k - 1, 0))
{
if (pos[i] == str.size() - 1)
continue;
for (int j = sa[pos[i] + 1]; str[i + k] == str[j + k]; k++);
lcp[pos[i]] = k;
}
}
bool cmp(int i, int j, int d)
{
if (pos[i] != pos[j])
return pos[i] < pos[j];
if (i + d < sa.size() && j + d < sa.size())
return pos[i + d] < pos[j + d];
return i + d > j + d;
}
vector<int> pos;
};