Time Limit: 149MS | Memory Limit: 1572864KB | 64bit IO Format: %lld & %llu |
Description
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".
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 consists of Q lines, the i-th contains a string which is the answer to the i-th asked question.
Input:
aaa
2
2
3
Output: aa
aaa
【题意】
给定一个字符串,询问次序为k的子串。
【思路】
SAM,名次
建好SAM后求出每个点往下有多少个串sum,然后根据sum访问并输出路径即可。
【代码】
1 #include<cstdio> 2 #include<cstring> 3 using namespace std; 4 5 const int N = 3*1e5+10; 6 7 char s[N]; 8 int root,last,sz,ch[N][26],fa[N],sum[N],l[N]; 9 void add(int x) { 10 int c=s[x]-‘a‘; 11 int p=last,np=++sz; last=np; 12 l[np]=x+1; 13 for(;p&&!ch[p][c];p=fa[p]) ch[p][c]=np; 14 if(!p) fa[np]=root; 15 else { 16 int q=ch[p][c]; 17 if(l[p]+1==l[q]) fa[np]=q; 18 else { 19 int nq=++sz; l[nq]=l[p]+1; 20 memcpy(ch[nq],ch[q],sizeof(ch[q])); 21 fa[nq]=fa[q]; 22 fa[np]=fa[q]=nq; 23 for(;p&&q==ch[p][c];p=fa[p]) ch[p][c]=nq; 24 } 25 } 26 } 27 28 int n,m,b[N],cnt[N]; 29 30 void get_sum() { 31 for(int i=1;i<=sz;i++) cnt[l[i]]++; 32 for(int i=1;i<=n;i++) cnt[i]+=cnt[i-1]; 33 for(int i=1;i<=sz;i++) b[cnt[l[i]]--]=i; 34 for(int i=sz;i;i--) { 35 int p=b[i]; sum[p]=1; 36 for(int j=0;j<26;j++) 37 sum[p]+=sum[ch[p][j]]; 38 } 39 } 40 41 int main() { 42 scanf("%s",s); 43 n=strlen(s); 44 root=last=++sz; 45 for(int i=0;i<n;i++) add(i); 46 get_sum(); 47 scanf("%d",&m); 48 while(m--) { 49 int x,p=root; scanf("%d",&x); 50 while(x) { 51 for(int c=0;c<26;c++)if(ch[p][c]) { 52 if(sum[ch[p][c]]>=x) { 53 putchar(‘a‘+c); 54 x--; p=ch[p][c]; 55 break; 56 } 57 else x-=sum[ch[p][c]]; 58 } 59 } 60 puts(""); 61 } 62 return 0; 63 }
原文:http://www.cnblogs.com/lidaxin/p/5198797.html