Description
Little Daniel loves to play with strings! He always finds different ways to have fun with strings! Knowing that, his friend Kinan decided to test his skills so he gave him a string S and asked him Q questions of the form:
If all distinct substrings of string S were sorted lexicographically, which one will be the K-th smallest?
After knowing the huge number of questions Kinan will ask, Daniel figured out that he can’t do this alone. Daniel, of course, knows your exceptional programming skills, so he asked you to write him a program which given S will answer Kinan’s questions.Example:
S = “aaa” (without quotes)
substrings of S are “a” , “a” , “a” , “aa” , “aa” , “aaa”. The sorted list of substrings will be:
“a”, “aa”, “aaa”.
Input
In the first line there is Kinan’s string S (with length no more than 90000 characters). It contains only small letters of English alphabet. The second line contains a single integer Q (Q <= 500) , the number of questions Daniel will be asked. In the next Q lines a single integer K is given (0 < K < 2^31).Output
Output consists of Q lines, the i-th contains a string which is the answer to the i-th asked question.Example
Input:
aaa
2
2
3Output:
aa
aaa
先构造出S的SAM,然后算出到某个节点还可以到达多少个不同子串,就可以了..
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
using namespace std;
const int Maxn = 90010;
int F[Maxn*2], d[Maxn*2], ch[Maxn*2][26], tot, now, f[Maxn*2];
char s[Maxn*2]; int len;
int Rsort[Maxn*2], rk[Maxn*2];
int copy ( int p, int c ){
int x = ++tot, y = ch[p][c];
d[x] = d[p]+1;
for ( int i = 0; i < 26; i ++ ) ch[x][i] = ch[y][i];
F[x] = F[y]; F[y] = x;
while ( ~p && ch[p][c] == y ){ ch[p][c] = x; p = F[p]; }
return x;
}
void add ( int c ){
int p, o;
if ( p = ch[now][c] ){
if ( d[p] != d[now]+1 ) copy ( now, c );
now = ch[now][c];
}
else {
d[o=++tot] = d[now]+1; p = now; now = o;
while ( ~p && !ch[p][c] ){ ch[p][c] = o; p = F[p]; }
F[o] = ~p ? ( d[ch[p][c]] == d[p]+1 ? ch[p][c] : copy ( p, c ) ) : 0;
}
}
int m;
int main (){
int i, j, k;
scanf ( "%s", s+1 ); len = strlen (s+1);
F[0] = -1;
for ( i = 1; i <= len; i ++ ) add (s[i]-'a');
for ( i = 1; i <= tot; i ++ ){ Rsort[d[i]] ++; f[i] = 1; }
for ( i = 1; i <= len; i ++ ) Rsort[i] += Rsort[i-1];
for ( i = tot; i >= 1; i -- ) rk[Rsort[d[i]]--] = i;
for ( i = tot; i >= 1; i -- ){
for ( j = 0; j < 26; j ++ ) if ( ch[rk[i]][j] > 0 ) f[rk[i]] += f[ch[rk[i]][j]];
}
scanf ( "%d", &m );
for ( i = 1; i <= m; i ++ ){
int x;
scanf ( "%d", &x );
now = 0;
while (x){
for ( j = 0; j < 26; j ++ ){
if ( ch[now][j] ){
if ( x <= f[ch[now][j]] ){
printf ( "%c", j+'a' );
now = ch[now][j];
x --;
break;
}
else x -= f[ch[now][j]];
}
}
}
printf ( "\n" );
}
return 0;
}

本文介绍了一个字符串匹配的问题,即如何找出给定字符串的所有不同子串,并按字典序排序后的第K个子串。通过构建字符串的后缀自动机(SAM),实现了一种高效的算法解决方案。
221

被折叠的 条评论
为什么被折叠?



