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 题解:
这题磨人啊,SPOJ跑的又慢,时限又短,压了一晚上常。
思路如下:
SAM满足性质:dfs序每一步走出来的都是一个子串,且满足从小到大顺序,关键满足不重不漏.
那么根据性质可以想出:沿着SAM走k步就是k-th子串了.
考虑优化:
记录size[x]为x节点往下可以产生的子串个数,和上题类似可以拓扑序搞出来 然后如果小于rk那么就直接减去即可.
压常技巧:
1.rg inline 不解释
2.不知为何,代码中k的输入写在函数内就快了4倍 懂得可以评论下....
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cmath>
#define RG register
using namespace std;
const int N=,M=;
char s[M];int n=,cnt=,last=,cur=,fa[M],ch[M][],dis[M],size[M];
void build(int c){
last=cur;cur=++cnt;
int p=last;
dis[cur]=++n;
for(;p && !ch[p][c];p=fa[p])ch[p][c]=cur;
if(!p)fa[cur]=;
else{
int q=ch[p][c];
if(dis[q]==dis[p]+)fa[cur]=q;
else{
int nt=++cnt;
dis[nt]=dis[p]+;
memcpy(ch[nt],ch[q],sizeof(ch[q]));
fa[nt]=fa[q];fa[q]=fa[cur]=nt;
for(;ch[p][c]==q;p=fa[p])ch[p][c]=nt;
}
}
}
int sa[M];int c[M];
void Flr(){
int p;
for(RG int i=;i<=cnt;i++)c[dis[i]]++;
for(RG int i=;i<=n;i++)c[i]+=c[i-];
for(RG int i=cnt;i;i--)sa[c[dis[i]]--]=i;
for(RG int i=cnt;i;i--){
p=sa[i];
size[p]=;
for(int j=;j<=;j++)
size[p]+=size[ch[p][j]];
}
}
void dfs(){
RG int u,x=,rk;
scanf("%d",&rk);
while(rk)
{
for(int i=;i<=;i++){
u=ch[x][i];
if(!u)continue;
if(size[u]>=rk){
putchar('a'+i);
x=u;rk--;break;
}
else rk-=size[u];
}
}
puts("");
}
void work(){
scanf("%s",s);
for(RG int i=,l=strlen(s);i<l;i++)build(s[i]-'a');
Flr();
int Q,x;
scanf("%d",&Q);
while(Q--)dfs();
}
int main()
{
work();
return ;
}