洛谷 SP7258 SUBLEX - Lexicographical Substring Search
洛谷 SP7258 SUBLEX - Lexicographical Substring Search
Problem
先给你一个字符串s,后有T次询问。询问这个字符串的所有本质不同的子串中第k小的子串。
\(\mid s\mid\le9\times 10^4,T\le500\)
Solution
这也是一道SAM的模板题。
字典序第k小子串对应SAM中字典序第k小的路径。用拓扑排序计算每个状态的路径数之后,我们从SAM的根节点开始跑,类比平衡树等数据结构中的查询第k小的数这一个操作,很容易就可以找到第k小的路径。
Code
/**************************************************************
* Problem: SP7258
* Author: Vanilla_chan
* Date: 20210325
* E-Mail: Vanilla_chan@outlook.com
**************************************************************/
//预编译部分已略
namespace SAM
{
const int maxn=90010;
struct state
{
int len,link;
LL f;
mapnxt;
state operator=(const state& z)
{
len=z.len;
link=z.link;
nxt=z.nxt;
f=0;
return *this;
}
}st[maxn<<1];
int cnt=1,last=1;
void insert(const char& ch)
{
int p=last;
int cur=last=++cnt;
st[cur].len=st[p].len+1;
st[cur].f=1;
while(p&&!st[p].nxt.count(ch))
{
st[p].nxt[ch]=cur;
p=st[p].link;
}
if(!p)
{
st[cur].link=1;
}
else
{
int q=st[p].nxt[ch];
if(st[p].len+1==st[q].len)//
{
st[cur].link=q;
}
else
{
int nq=++cnt;
st[nq]=st[q];
st[nq].len=st[p].len+1;//
st[q].link=st[cur].link=nq;
while(p&&st[p].nxt[ch]==q)
{
st[p].nxt[ch]=nq;
p=st[p].link;
}
}
}
}
};
#define N 90010
LL ans;
int in[N<<1];
int l,r;
int q[N<<1];
int sze[N<<1];
void top()
{
using namespace SAM;
for(int i=1;i<=cnt;i++)
{
for(map::iterator it=st[i].nxt.begin();it!=st[i].nxt.end();it++)
{
in[it->second]++;
}
}
l=1,r=0;
for(int i=1;i<=cnt;i++) if(in[i]==0) q[++r]=i;
for(;l<=r;l++)
{
for(map::iterator it=st[q[l]].nxt.begin();it!=st[q[l]].nxt.end();it++)
{
in[it->second]--;
if(in[it->second]==0)
{
q[++r]=it->second;
}
}
}
for(int i=r;i>=1;i--)
{
sze[q[i]]=1;
for(map::iterator it=st[q[i]].nxt.begin();it!=st[q[i]].nxt.end();it++)
{
sze[q[i]]+=sze[it->second];
}
}
}
void ask(int x,int k)
{
using namespace SAM;
while(k)
{
for(map::iterator it=st[x].nxt.begin();it!=st[x].nxt.end();it++)
{
if(sze[it->second]>=k)
{
putchar(it->first);
x=it->second;
k--;
break;
}
else k-=sze[it->second];
}
}
cout<>str;
for(int i=0;i>k;
ask(1,k);
}
return 0;
}
extend
注意这道题是求本质不同的,即,对于本质相同、不同位置子串,看作是一种。
接下来不妨去做一下洛谷 P3975 [TJOI2015]弦论,求对于所有子串的所有子串(不同位置的相同子串算作多个)的第k小子串。