【BZOJ3998】[TJOI2015]弦论

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

题解:先跑后缀自动机,再处理出SAM的拓扑序,处理出在每个节点结束的子串个数,最后扫一遍SAM。如果在当前儿子的子树中结束的子串个数<k,那么k-=个数,再扫下一个儿子。

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int maxn=1000010;
int n,T,K,last,tot;
int st[maxn],tb[maxn],pre[maxn],ch[maxn][26],dep[maxn],r[maxn],f[maxn];
char str[maxn];
void add(int x)
{
int p=last,np=++tot;
last=np,dep[np]=dep[p]+1;
for(;p&&!ch[p][x];p=pre[p]) ch[p][x]=np;
if(!p) pre[np]=1;
else
{
int q=ch[p][x];
if(dep[q]==dep[p]+1) pre[np]=q;
else
{
int nq=++tot;
memcpy(ch[nq],ch[q],sizeof(ch[q]));
dep[nq]=dep[p]+1,pre[nq]=pre[q],pre[q]=pre[np]=nq;
for(;p&&ch[p][x]==q;p=pre[p]) ch[p][x]=nq;
}
}
}
int main()
{
last=tot=1;
scanf("%s%d%d",str,&T,&K),n=strlen(str);
int i,p,j;
for(i=1;i<=n;i++) add(str[i-1]-'a');
for(i=p=1;i<=n;i++) p=ch[p][str[i-1]-'a'],r[p]++;
for(i=1;i<=tot;i++) st[dep[i]]++;
for(i=1;i<=n;i++) st[i]+=st[i-1];
for(i=tot;i>=1;i--) tb[st[dep[i]]--]=i;
if(T) for(i=tot;i>=1;i--) r[pre[tb[i]]]+=r[tb[i]];
else for(i=1;i<=tot;i++) r[i]=1;
for(i=tot,r[1]=0;i>=1;i--) for(f[tb[i]]=r[tb[i]],j=0;j<26;j++) f[tb[i]]+=f[ch[tb[i]][j]];
if(f[1]<K)
{
printf("-1");
return 0;
}
p=1;
while(K>r[p])
{
for(i=0,K-=r[p];i<26&&K>f[ch[p][i]];i++) K-=f[ch[p][i]];
printf("%c",'a'+i),p=ch[p][i];
}
return 0;
}

最新文章

  1. mysql : utf8mb4 的问题
  2. ECharts使用心得总结(二)
  3. (27)odoo 中改变菜单动作的默认视图
  4. centos安装lxml和pyspider
  5. 关于网上流传的四个原版Windows XP_SP2全面了解
  6. 反编译APK终结教程
  7. Mybatis.net与MVC入门配置及联合查询动态SQL拼接和简单事务
  8. Maven模块聚合与继承
  9. 深入Java单例模式
  10. PyQt QListWidget修改列表项item的行高
  11. uclibc和glibc的差别
  12. 根据关键字获取高德地图poi信息
  13. day 7-3 僵尸进程,孤儿进程与守护进程
  14. 关于Jedis是否线程安全的测试
  15. PHP中self和this的用法区别
  16. tp5 Excel导入
  17. Windows 系统安装多个版本JDK, 修改环境变量不生效
  18. Paypal Rest Api自定义物流地址(跳过填写物流地址)
  19. ssh 第一次登录输入yes 问题
  20. Python中则正则表达式

热门文章

  1. Docker默认存储路径修改
  2. mac重置蓝牙模块
  3. 访问vector元素方法的效率比较(转)
  4. 复选框input:checkbox
  5. 简单模拟javaScript面向对象
  6. 檢查php文件中是否含有bom的php文件
  7. left与margin-left区别
  8. NIO之DatagramChannel
  9. FPGA+DSP SRIO通信(一)——DSP端参数设置(通道)
  10. 605. Can Place Flowers【easy】