-
Notifications
You must be signed in to change notification settings - Fork 0
/
11479_lcp.cpp
82 lines (82 loc) · 1.65 KB
/
11479_lcp.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
// 211214 #11479 서로 다른 부분 문자열의 개수 2 Platinum II
// lcp
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <string>
#include <unordered_map>
#include <unordered_set>
#define all(v) (v).begin(), (v).end()
#define press(v) (v).erase(unique(all(v)), (v).end())
using namespace std;
typedef long long ll;
typedef pair<int, int> pi;
typedef pair<int, pi> pii;
typedef pair<ll, ll> pl;
typedef pair<ll, pl> pll;
const int MAX = 1000011;
const int INF = 0x3f3f3f3f;
const ll LNF = 0x3f3f3f3f3f3f3f3f;
const int MOD = 1e9 + 7;
string s;
int N, sa[MAX], group[MAX], t, lcp[MAX], tmp[MAX], r[MAX];
bool cmp(int x, int y) {
if (group[x] == group[y]) {
x += t; y += t;
if (x < N && y < N)
return group[x] < group[y];
return x > y;
}
return group[x] < group[y];
}
void getSA() {
for (int i = 0; i < N; i++) {
sa[i] = i;
group[i] = s[i] - 'a';
}
for (t = 1; t <= N; t *= 2) {
sort(sa, sa + N, cmp);
tmp[sa[0]] = 0;
for (int i = 1; i < N; i++) {
tmp[sa[i]] = tmp[sa[i - 1]];
if (cmp(sa[i - 1], sa[i]))
tmp[sa[i]]++;
}
for (int i = 0; i < N; i++)
group[i] = tmp[i];
}
}
void getLCP() {
for (int i = 0; i < N; i++) {
r[sa[i]] = i;
}
int h = 0;
for (int i = 0; i < N; i++) {
if (r[i]) {
int j = sa[r[i] - 1];
while (s[i + h] == s[j + h])h++;
lcp[r[i]] = h;
}
if (h)
h--;
}
}
int main() {
cin.tie(0)->sync_with_stdio(0);
cin >> s;
N = s.length();
getSA();
getLCP();
// if lcp, duplicate substring
ll ans = 1LL * N * (1LL * N + 1) / 2;
for (int i = 0; i < N; i++) {
ans -= 1LL * lcp[i];
}
cout << ans;
}