-
Notifications
You must be signed in to change notification settings - Fork 169
/
Distinct Substrings.cpp
70 lines (61 loc) · 1.38 KB
/
Distinct Substrings.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
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxN = 1e5+5;
struct Node {
ll dp;
int len, link;
map<char,int> nxt;
} node[2*maxN];
char S[maxN];
int N, sz, last;
void init(){
node[0].len = 0;
node[0].link = -1;
sz = 1;
last = 0;
}
void extend(char c){
int cur = sz++;
node[cur].len = node[last].len + 1;
int p = last;
while(p != -1 && !node[p].nxt.count(c)){
node[p].nxt[c] = cur;
p = node[p].link;
}
if(p == -1){
node[cur].link = 0;
} else {
int q = node[p].nxt[c];
if(node[p].len + 1 == node[q].len){
node[cur].link = q;
} else {
int clone = sz++;
node[clone].len = node[p].len + 1;
node[clone].nxt = node[q].nxt;
node[clone].link = node[q].link;
while(p != -1 && node[p].nxt[c] == q){
node[p].nxt[c] = clone;
p = node[p].link;
}
node[q].link = node[cur].link = clone;
}
}
last = cur;
}
void calc(int u = 0){
node[u].dp = 1;
for(const auto& [c, v] : node[u].nxt){
if(!node[v].dp) calc(v);
node[u].dp += node[v].dp;
}
}
int main(){
scanf(" %s", S);
N = (int) strlen(S);
init();
for(int i = 0; i < N; i++)
extend(S[i]);
calc();
printf("%lld\n", node[0].dp-1);
}