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). OutputOutput consists of Q lines, the i-th contains a string which is the
answer to the i-th asked question.
后缀自动机解法见【这里】。
建出来sa,把询问排序之后在sa上扫描一遍,每个后缀会贡献
n−sa[i]+1−height[i]
个本质不同的子串。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct query
{
int id,k;
bool operator < (const query &qq) const
{
return k<qq.k;
}
}a[510];
char s[200010];
int sa[200010],rank[200010],hei[200010],cnt[200010],f[200010],ansp[510],anslen[510],
n,m=26,q;
int main()
{
int p,now=0;
scanf("%s",s+1);
n=strlen(s+1);
for (int i=1;i<=n;i++) cnt[rank[i]=s[i]-'a'+1]++;
for (int i=2;i<=m;i++) cnt[i]+=cnt[i-1];
for (int i=n;i;i--) sa[cnt[rank[i]]--]=i;
for (int k=1;k<=n;k<<=1)
{
p=0;
for (int i=n-k+1;i<=n;i++) f[++p]=i;
for (int i=1;i<=n;i++) if (sa[i]>k) f[++p]=sa[i]-k;
for (int i=1;i<=m;i++) cnt[i]=0;
for (int i=1;i<=n;i++) cnt[rank[f[i]]]++;
for (int i=2;i<=m;i++) cnt[i]+=cnt[i-1];
for (int i=n;i;i--) sa[cnt[rank[f[i]]]--]=f[i];
for (int i=1;i<=n;i++) f[i]=rank[i];
rank[sa[1]]=1;
for (int i=2;i<=n;i++)
rank[sa[i]]=rank[sa[i-1]]+
(f[sa[i]]!=f[sa[i-1]]||f[sa[i]+k]!=f[sa[i-1]+k]);
if (rank[sa[n]]>=n) break;
m=rank[sa[n]];
}
for (int i=1;i<=n;i++)
{
hei[rank[i]]=hei[rank[i-1]];
if (hei[rank[i]]) hei[rank[i]]--;
while (s[i+hei[rank[i]]]==s[sa[rank[i]-1]+hei[rank[i]]]) hei[rank[i]]++;
}
scanf("%d",&q);
for (int i=1;i<=q;i++)
{
scanf("%d",&a[i].k);
a[i].id=i;
}
sort(a+1,a+q+1);
p=1;
for (int i=1;i<=q;i++)
{
while (now+n-sa[p]+1-hei[p]<a[i].k)
{
now+=n-sa[p]+1-hei[p];
p++;
}
ansp[a[i].id]=sa[p];
anslen[a[i].id]=hei[p]+a[i].k-now;
}
for (int i=1;i<=q;i++)
{
for (int j=ansp[i];j<=ansp[i]+anslen[i]-1;j++) putchar(s[j]);
putchar('\n');
}
}