#include <bits/stdc++.h>
using namespace std;
const int N = 1100010;
char s[N];
int las = 1, node = 1;
int fa[N], len[N], siz[N], ch[N][26];
void extend (int c) {
register int p, q, x, y;
p = las, q = ++node; las = q;
len[q] = len[p] + 1; siz[q] = 1;
while (p != 0 && ch[p][c] == 0) {
ch[p][c] = q;
p = fa[p];
}
if (p == 0) {
fa[q] = 1;
} else {
x = ch[p][c];
if (len[x] == len[p] + 1) {
fa[q] = x;
} else {
y = ++node;
fa[y] = fa[x];
fa[x] = fa[q] = y;
len[y] = len[p] + 1;
memcpy (ch[y], ch[x], sizeof (ch[x]));
while (p != 0 && ch[p][c] == x) {
ch[p][c] = y;
p = fa[p];
}
}
}
}
int t, k, nd[N], bin[N]; long long sum[N];
void output (int u) {
if (k <= siz[u]) return;
k -= siz[u];
register int i;
for (i = 0; i < 26; ++i) {
if (ch[u][i]) {
if (k > sum[ch[u][i]]) {
k -= sum[ch[u][i]];
} else {
printf ("%c", i + 'a');
output (ch[u][i]);
return;
}
}
}
}
int main () {
scanf ("%s %d %d", s, &t, &k);
register int i, j, n;
n = strlen (s);
for (i = 0; i < n; ++i) extend (s[i] - 'a');
for (i = 1; i <= node; ++i) bin[len[i]]++;
for (i = 1; i <= node; ++i) bin[i] += bin[i - 1];
for (i = 1; i <= node; ++i) nd[bin[len[i]]--] = i;
for (i = node; i >= 1; --i) siz[fa[nd[i]]] += siz[nd[i]];
for (i = 1; i <= node; ++i) t == 0 ? (sum[i] = siz[i] = 1) : (sum[i] = siz[i]);
siz[1] = sum[1] = 0;
for (i = node; i >= 1; --i) {
for (j = 0; j < 26; ++j) {
if (ch[nd[i]][j]) {
sum[nd[i]] += sum[ch[nd[i]][j]];
}
}
}
if (sum[1] < k) {
puts ("-1");
} else {
output (1);
}
}
原文:https://www.cnblogs.com/maomao9173/p/10452644.html