forked from mrsac7/CSES-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
2110 - Substring Distribution.cpp
72 lines (63 loc) · 1.53 KB
/
2110 - Substring Distribution.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
/*
Problem Name: Substring Distribution
Problem Link: https://cses.fi/problemset/task/2110
Author: Sachin Srivastava (mrsac7)
*/
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define endl '\n'
const int mxN = 1e5+5;
int sa[mxN], pos[mxN], tmp[mxN], lcp[mxN];
int gap, N;
string S;
bool comp(int x, int y) {
if (pos[x] != pos[y])
return pos[x] < pos[y];
x += gap;
y += gap;
return (x < N && y < N) ? pos[x] < pos[y] : x > y;
}
void suffix() {
for (int i = 0; i < N; i++)
sa[i] = i, pos[i] = S[i];
for (gap = 1;; gap <<= 1) {
sort(sa, sa+N, comp);
for (int i = 0; i < N-1; i++)
tmp[i+1] = tmp[i] + comp(sa[i], sa[i+1]);
for (int i = 0; i < N; i++)
pos[sa[i]] = tmp[i];
if (tmp[N - 1] == N - 1)
break;
}
}
void build_lcp() {
for (int i = 0, k = 0; i < N; i++) if (pos[i] != N-1) {
int j = sa[pos[i] + 1];
while (S[i + k] == S[j + k])
k++;
lcp[pos[i]] = k;
if (k) k--;
}
}
int pre[mxN];
signed main(){
ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#ifdef LOCAL
freopen("input.txt", "r" , stdin);
freopen("output.txt", "w", stdout);
#endif
cin>>S; N = S.size();
suffix();
build_lcp();
int prev = 0;
for (int i = 0; i < N; i++) {
pre[prev + 1]++;
pre[N - sa[i] + 1]--;
prev = lcp[i];
}
for (int i = 1; i <= N; i++) {
cout << pre[i] << ' ' ;
pre[i+1] += pre[i];
}
}