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
3
Output:
aa
aaa
Edited: Some input file contains garbage at the end. Do not process them.
后缀数组做法很显然,后缀自动机做法
就是找存在的nxt[p][i] 遍历找就好,每个父节点保存的是由该点出发的子串的数量,小于k,就把这些减掉,如果有大于它的,那么k–,代表这个字母我们需要的,然后继续往下走 p=nxt[p][i]
#include
using namespace std;
const int maxn = 200000+5;
int last,tail;
int Max[maxn],cnt[maxn];
int nxt[maxn][26],fail[maxn];
char sa[maxn],sb[maxn];
int Maxi[maxn];
typedef long long ll;
ll sz[maxn];
inline void build(char *s)
{
while(*s)
{
int p=last,t=++tail,c=*s++-'a';
Max[t]=Max[p]+1;
while(p&&!nxt[p][c])
nxt[p][c]=t,p=fail[p];
if(p)
{
int q=nxt[p][c];
if(Max[q]==Max[p]+1)
fail[t]=q;
else
{
int k=++tail;
fail[k]=fail[q];
fail[t]=fail[q]=k;
Max[k]=Max[p]+1;
memcpy(nxt[k],nxt[q],sizeof(nxt[q]));
while(p&&nxt[p][c]==q)
nxt[p][c]=k,p=fail[p];
}
}
else
fail[t]=1;
last=t;
}
}
int q[maxn];
void solve(ll k)
{
int p=1;
while(k)
{
for(int i=0;i<26;i++)
{
if(nxt[p][i])
{
if(sz[nxt[p][i]]>=k)
{
putchar('a'+i);
k--;
p=nxt[p][i];
break;
}
else k-=sz[nxt[p][i]];
}
}
}
}
int b[maxn];
int main()
{
scanf("%s",sa);
last=1,tail=1;
build(sa);
int hh=strlen(sa);
for(int i=1;i<=tail;i++) cnt[Max[i]]++;
for(int i=1;i<=hh;i++) cnt[i]+=cnt[i-1];
for(int i=1;i<=tail;i++) b[cnt[Max[i]]--]=i;
for(int i=tail;i>=1;i--)
{
int p=b[i];
sz[p]=1;
for(int j=0;j<26;j++)
sz[p]+=sz[nxt[p][j]];
}
int q;
scanf("%d",&q);
while(q--)
{
int n;
scanf("%d",&n);
solve(n);
printf("\n");
}
}