Description
对于一个给定长度为N的字符串,求它的第K小子串是什么。
Input
第一行是一个仅由小写英文字母构成的字符串S
第二行为两个整数T和K,T为0则表示不同位置的相同子串算作一个。T=1则表示不同位置的相同子串算作多个。K的意义如题所述。
Output
输出仅一行,为一个数字串,为第K小的子串。如果子串数目不足K个,则输出-1
Sample Input
aabc 0 3
Sample Output
aab
Hint
N<=5*10^5
T<2
K<=10^9
题意:
没什么好解释的。
解法:
利用后缀自动机,开数组cnt存储当前结点包含的字符串个数,sum存储后继结点包含的字符串个数(相当于以此为前缀的字符串个数),拓扑排序求出endpos,对于t=1,不同位置的相同子串算两个,此时cnt就是当前结点的endpos个数,对于t=0,不同位置的相同子串算一个,此时cnt就是1。注意源点(也就是1)的cnt和sum在计算结束后要重新赋值为0,因为源点是空的。
处理完毕后从源点进行dfs,按顺序遍历所有的26个分支(相当于字典序),对于存在的分支,如果它之后的字符个数比k小,说明还没有到第k小的子串,从k中减去字符串个数(相当于去掉了这么多个子串),继续遍历下一个分支,如果大于等于k,说明该分支已经到了第k小的子串,输出对应的字母,减去该字母对应的字符串个数,如果k依然大于0,意味着还没到第k小的子串,对该分支进行dfs,遍历结束(当前分支已经满了k个,不需要遍历其他分支了)。
好了我承认,其实我就是在对着大佬的代码脑补。
大佬的代码:https://www.cnblogs.com/cjyyb/p/8449762.html
代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<stdlib.h>
#include<cstring>
using namespace std;
const int N=1e6+10;
struct node{
int ch[26];
int len,fa;
}dian[N];
int k,t,lens,las=1,tot=1;
int a[N],b[N],sum[N],cnt[N];
char s[N];
int add(int c){
int p=las;int np=las=++tot;
dian[np].len=dian[p].len+1;
for(;p&&!dian[p].ch[c];p=dian[p].fa)dian[p].ch[c]=np;
if(!p)dian[np].fa=1;
else{
int q=dian[p].ch[c];
if(dian[p].len+1==dian[q].len)dian[np].fa=q;
else{
int nq=++tot;dian[nq]=dian[q];
dian[nq].len=dian[p].len+1;
dian[q].fa=dian[np].fa=nq;
for(;p&&dian[p].ch[c]==q;p=dian[p].fa)dian[p].ch[c]=nq;
}
}
cnt[np]=1;
}
void dfs(int u,int k){
for(int i=0;i<26;i++){
if(!dian[u].ch[i])continue;
if(sum[dian[u].ch[i]]<k)k-=sum[dian[u].ch[i]];
else{
printf("%c",i+'a');
k-=cnt[dian[u].ch[i]];
if(k>0)dfs(dian[u].ch[i],k);
return;
}
}
}
int main()
{
scanf("%s%d%d",s+1,&t,&k);
lens=strlen(s+1);
for(int i=1;i<=lens;i++)add(s[i]-'a');
for(int i=1;i<=tot;i++)a[dian[i].len]++;
for(int i=1;i<=tot;i++)a[i]+=a[i-1];
for(int i=1;i<=tot;i++)b[a[dian[i].len]--]=i;
for(int i=tot;i>=1;i--)cnt[dian[b[i]].fa]+=cnt[b[i]];
for(int i=1;i<=tot;i++){
if(t==0)sum[i]=cnt[i]=1;
else sum[i]=cnt[i];
}
sum[1]=cnt[1]=0;
for(int i=tot;i>=1;i--){
for(int j=0;j<26;j++){
if(dian[b[i]].ch[j])sum[b[i]]+=sum[dian[b[i]].ch[j]];
}
}
if(k>sum[1])printf("-1\n");
else dfs(1,k),printf("\n");
return 0;
}