Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8a1eb19

Browse files
Add code for suffix array
1 parent d31f687 commit 8a1eb19

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

‎suffix_array.cpp

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
#include <bits/stdc++.h>
2+
#define ll long long
3+
using namespace std;
4+
5+
struct ranking {
6+
ll index;
7+
ll first;
8+
ll second;
9+
};
10+
11+
bool comp(ranking a, ranking b) {
12+
if (a.first == b.first) {
13+
return a.second < b.second;
14+
}
15+
return a.first < b.first;
16+
}
17+
18+
vector<ll> build_suffix_array(string s) {
19+
const ll n = s.length();
20+
const ll lgn = ceil(log2(n));
21+
22+
// vector to hold final suffix array result
23+
vector<ll> sa(n);
24+
25+
// P[i][j] holds the ranking of the j-th suffix
26+
// after comparing the first 2^i characters
27+
// of that suffix
28+
ll P[lgn][n];
29+
30+
// vector to store ranking tuples of suffixes
31+
vector<ranking> ranks(n);
32+
33+
ll i, j, step = 1;
34+
for(j = 0; j < n; j++) {
35+
P[0][j] = s[j] - 'a';
36+
}
37+
38+
for(i = 1; i <= lgn; i++, step++) {
39+
for(j = 0; j < n; j++) {
40+
ranks[j].index = j;
41+
ranks[j].first = P[i-1][j];
42+
ranks[j].second = (j + pow(2,i-1) < n) ? P[i-1][j + (ll)(pow(2,i-1))] : -1;
43+
}
44+
45+
sort(ranks.begin(), ranks.end(), comp);
46+
47+
for(j = 0; j < n; j++) {
48+
P[i][ranks[j].index] = (j > 0 && ranks[j].first == ranks[j-1].first && ranks[j].second == ranks[j-1].second) ? P[i][ranks[j-1].index] : j;
49+
}
50+
}
51+
52+
step -= 1;
53+
54+
for(i = 0; i < n; i++) {
55+
sa[P[step][i]] = i;
56+
}
57+
58+
return sa;
59+
}
60+
61+
int main() {
62+
string s;
63+
cin >> s;
64+
vector<ll> sa = build_suffix_array(s);
65+
for(ll i = 0; i < s.length(); i++) {
66+
cout << i << " : " << sa[i] << endl;
67+
}
68+
return 0;
69+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /