-
Notifications
You must be signed in to change notification settings - Fork 169
/
Substring Order I.cpp
88 lines (78 loc) · 1.74 KB
/
Substring Order I.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
#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];
vector<char> ans;
char S[maxN];
int N, sz, last;
ll K;
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;
}
}
void dfs(int u, ll k){
if(k < 0) return;
for(const auto& [c, v] : node[u].nxt){
if(node[v].dp <= k) k -= node[v].dp;
else {
ans.push_back(c);
dfs(v, k-1);
return;
}
}
}
int main(){
scanf(" %s %lld", S, &K);
N = (int) strlen(S);
init();
for(int i = 0; i < N; i++)
extend(S[i]);
calc();
dfs(0, K-1);
int M = (int) ans.size();
for(int i = 0; i < M; i++)
printf("%c", ans[i]);
printf("\n");
}