-
Notifications
You must be signed in to change notification settings - Fork 177
/
Copy pathRepeating Substring.cpp
92 lines (81 loc) · 2.05 KB
/
Repeating Substring.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
#include <bits/stdc++.h>
using namespace std;
const int maxN = 1e5+5;
struct Node {
int len, link, cnt, firstpos;
map<char,int> nxt;
} node[2*maxN];
char S[maxN];
bool vis[2*maxN];
int N, sz, last, bestidx, bestlen;
void extend(char c){
int cur = sz++;
node[cur].cnt = 1;
node[cur].firstpos = node[last].len;
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;
node[clone].firstpos = node[q].firstpos;
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 init(){
node[0].len = 0;
node[0].link = -1;
sz = 1;
last = 0;
}
void update_cnts(){
vector<int> states_by_len[sz];
for(int i = 0; i < sz; i++)
states_by_len[node[i].len].push_back(i);
for(int i = sz-1; i >= 0; i--)
for(int u : states_by_len[i])
if(node[u].link != -1)
node[node[u].link].cnt += node[u].cnt;
}
void dfs(int u = 0){
vis[u] = true;
if(node[u].len > bestlen && node[u].cnt > 1 && u != 0){
bestidx = node[u].firstpos - node[u].len + 1;
bestlen = node[u].len;
}
for(const auto& [c, v] : node[u].nxt)
if(!vis[v])
dfs(v);
}
int main(){
scanf(" %s", S);
N = (int) strlen(S);
init();
for(int i = 0; i < N; i++)
extend(S[i]);
update_cnts();
bestlen = -1;
dfs();
if(bestlen == -1) printf("-1\n");
else {
for(int i = 0; i < bestlen; i++)
printf("%c", S[bestidx+i]);
}
}