SUBLEX - Lexicographical Substring Search
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.
如果某个字符串再s中重复出现,将其看做一个子串。
题解:后缀自动机
从根节点到每个节点的路径就对应着原串的子串。因为排名的时候不计算重复子串,所以我直接按照拓扑序进行dp,计算出每个到达每个位置的排名。查询的时候直接根据大小关系在后缀自动机上匹配即可。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#define N 200003
using namespace std;
int n,m,cnt,last,p,q,np,nq,root;
int ch[N][30],fa[N],l[N],size[N],v[N],pos[N];
char s[N];
void extend(int x)
{
int c=s[x]-'a';
p=last; np=++cnt; last=np; l[np]=x;
for (;p&&!ch[p][c];p=fa[p]) ch[p][c]=np;
if (!p) fa[np]=root;
else {
q=ch[p][c];
if (l[q]==l[p]+1) fa[np]=q;
else {
nq=++cnt; l[nq]=l[p]+1;
memcpy(ch[nq],ch[q],sizeof ch[nq]);
fa[nq]=fa[q];
fa[q]=fa[np]=nq;
for (;ch[p][c]==q;p=fa[p]) ch[p][c]=nq;
}
}
}
void solve()
{
for (int i=cnt;i>=1;i--){
int t=pos[i];
size[t]++;
for (int j=0;j<26;j++)
if (ch[t][j]) size[t]+=size[ch[t][j]];
}
}
void pri(int x)
{
p=1;
while (x){
for (int i=0;i<26;i++)
if (ch[p][i])
if (x>size[ch[p][i]]) x-=size[ch[p][i]];
else {
putchar(97+i);
p=ch[p][i]; x--;
break;
}
}
}
int main()
{
freopen("a.in","r",stdin);
scanf("%s",s+1);
n=strlen(s+1); last=root=++cnt;
for (int i=1;i<=n;i++) extend(i);
for (int i=1;i<=cnt;i++) v[l[i]]++;
for (int i=1;i<=cnt;i++) v[i]+=v[i-1];
for (int i=1;i<=cnt;i++) pos[v[l[i]]--]=i;
solve();
scanf("%d",&m);
for (int i=1;i<=m;i++) {
int x; scanf("%d",&x);
pri(x);
printf("\n");
}
}