[Hacker Rank] String Function Calculation

String Function Calculation

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
#include <bits/stdc++.h>

using namespace std;

vector<int> sa(string& s) {
int t = 1, n = s.length();
vector<int> SA(n), g(n + 1), tg(n + 1);
for(int i = 0; i < n; i++) {
SA[i] = i;
g[i] = s[i] - 'a';
}

while(t <= n) {
g[n] = -1;
auto cmp = [&](int x, int y) {
if(g[x] == g[y])
return g[x + t] < g[y + t];
return g[x] < g[y];
};
sort(begin(SA), end(SA), cmp);

tg[SA[0]] = 0;
for(int i = 1; i < n; i++) {
tg[SA[i]] = tg[SA[i-1]] + cmp(SA[i-1], SA[i]);
}

g = tg;
t<<=1;
}

return SA;
}

vector<int> lcp(string& s, vector<int>& SA) {
int n = s.length(), len = 0;
vector<int> LCP(n), rsa(n);
for(int i = 0; i < n; i++)
rsa[SA[i]] = i;
for(int i = 0; i < n; i++) {
int k = rsa[i];
if(k) {
int j = SA[k-1];
while(s[i + len] == s[j + len]) ++len;
LCP[k] = len;
if(len) --len;
}
}
return LCP;
}
int solve(string& s) {
int res = 0, n = s.length();
auto SA = sa(s), LCP = lcp(s, SA);
vector<int> V(n, -1);
for(int i = 0; i < n; i++) {
int len = n - SA[i], j = i;
while(j < n and V[j] < len) {
V[j] = len;
res = max(res, len * (j - i + 1));
j++;
len = min(len, j < n ? LCP[j] : 0);
}
}
return res;
}
int main() {
string s;
cin>>s;
cout<<solve(s);

}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/19/PS/HackerRank/string-function-calculation/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.