-
Notifications
You must be signed in to change notification settings - Fork 438
/
Suffix-Array-with-Height(Doubling).cpp
138 lines (129 loc) · 1.91 KB
/
Suffix-Array-with-Height(Doubling).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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#include <cstdio>
#include <cstring>
#define STRING_LENGTH 200000
using namespace std;
struct sortinfo
{
int x, y, ord;
};
int l;
char s[STRING_LENGTH];
int rank[STRING_LENGTH * 2], sa[STRING_LENGTH], height[STRING_LENGTH];
void radix_sort(sortinfo *d)
{
static sortinfo _d[STRING_LENGTH], res[STRING_LENGTH];
static int c[STRING_LENGTH];
memset(c, 0, sizeof(c));
for (int i = 0; i < l; i++)
{
c[d[i].y]++;
}
for (int i = 1; i <= l; i++)
{
c[i] += c[i - 1];
}
for (int i = l - 1; i >= 0; i--)
{
_d[--c[d[i].y]] = d[i];
}
memset(c, 0, sizeof(c));
for (int i = 0; i < l; i++)
{
c[_d[i].x]++;
}
for (int i = 1; i <= l; i++)
{
c[i] += c[i - 1];
}
for (int i = l - 1; i >= 0; i--)
{
res[--c[_d[i].x]] = _d[i];
}
for (int i = 0; i < l; i++)
{
d[i] = res[i];
}
}
void init_rank()
{
static int c[256];
static sortinfo d[STRING_LENGTH];
int x = 1;
for (int i = 0; i < l; i++)
{
c[(int)s[i]] = 1;
}
for (int i = 0; i < 256; i++)
{
if (c[i] == 1)
{
c[i] = x++;
}
}
for (int i = 0; i < l; i++)
{
rank[i] = c[(int)s[i]];
}
for (int k = 1; k < l; k <<= 1)
{
for (int i = 0; i < l; i++)
{
d[i].x = rank[i];
d[i].y = rank[i + k];
d[i].ord = i;
}
radix_sort(d);
x = 1;
rank[d[0].ord] = 1;
for (int i = 1; i < l; i++)
{
rank[d[i].ord] = (d[i].x == d[i - 1].x && d[i].y == d[i - 1].y ? x : ++x);
}
if (x == l)
{
break;
}
}
}
void rank_to_sa()
{
for (int i = 0; i < l; i++)
{
sa[rank[i]] = i;
}
}
void init_height()
{
int k = 0;
for (int i = 0; i < l; i++)
{
if (k > 0)
{
k--;
}
if (rank[i] == l)
{
continue;
}
for (; s[i + k] == s[sa[rank[i] + 1] + k]; k++) ;
height[rank[i]] = k;
}
}
int main()
{
scanf("%s", s);
l = strlen(s);
init_rank();
rank_to_sa();
init_height();
for (int i = 1; i <= l; i++)
{
printf("%d ", sa[i] + 1);
}
printf("\n");
for (int i = 1; i < l; i++)
{
printf("%d ", height[i]);
}
return 0;
}