您的位置:首页 > 其它

spoj SUBLEX Lexicographical Substring Search【解法一】

2017-03-30 17:23 363 查看
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.

后缀数组解法见【这里】

建出SAM,求出每个节点对应的位置之后有多少个子串,然后对每个询问dfs一遍。

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
char s[200010];
int fa[200010],trans[200010][30],val[200010],cnt[200010],num[200010],a[200010],
n,q,tot=1,last=1;
int main()
{
/*  freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);*/
int p,np,q,nq,c,k;
scanf("%s",s+1);
n=strlen(s+1);
for (int i=1;i<=n;i++)
{
c=s[i]-'a'+1;
p=last;
val[np=++tot]=val[p]+1;
while (p&&!trans[p][c])
{
trans[p][c]=np;
p=fa[p];
}
if (!p) fa[np]=1;
else
{
q=trans[p][c];
if (val[q]==val[p]+1) fa[np]=q;
else
{
val[nq=++tot]=val[p]+1;
for (int j=1;j<=26;j++) trans[nq][j]=trans[q][j];
fa[nq]=fa[q];
fa[q]=fa[np]=nq;
while (p&&trans[p][c]==q)
{
trans[p][c]=nq;
p=fa[p];
}
}
}
last=np;
}
for (int i=1;i<=tot;i++) num[val[i]]++;
for (int i=1;i<=n;i++) num[i]+=num[i-1];
for (int i=1;i<=tot;i++) a[num[val[i]]--]=i;
for (int i=2;i<=tot;i++) cnt[i]=1;
for (int i=tot;i;i--)
for (int j=1;j<=26;j++)
cnt[a[i]]+=cnt[trans[a[i]][j]];
scanf("%d",&q);
while (q--)
{
scanf("%d",&k);
for (p=1;k;)
{
if (p!=1) k--;
if (!k) break;
for (int i=1;i<=26;i++)
if (trans[p][i])
{
if (k>cnt[trans[p][i]]) k-=cnt[trans[p][i]];
else
{
putchar(i+'a'-1);
p=trans[p][i];
break;
}
}
}
putchar('\n');
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  SAM