3277: 串
Time Limit: 10 Sec Memory Limit: 128 MBSubmit: 357 Solved: 144
[ Submit][ Status][ Discuss]
Description
字符串是oi界常考的问题。现在给定你n个字符串,询问每个字符串有多少子串(不包括空串)是所有n个字符串中至少k个字符串的子串(注意包括本身)。
Input
第一行两个整数n,k。
接下来n行每行一个字符串。
接下来n行每行一个字符串。
Output
输出一行n个整数,第i个整数表示第i个字符串的答案。
Sample Input
3 1
abc
a
ab
Sample Output
6 1 3
HINT
对于100%的数据,n,k,l<=100000
Source
题解:后缀自动机
这道题在预处理的时候与bzoj 2780是相同的。
我们要求每个字符串有多少子串是所有n个字符串中至少k个字符串的子串,先不考虑k个字符串的限制,该如何求解一共有多少子串呢?
我们记录了从根到每个状态最长的串的长度。l[i]-l[fa[i]]记录的就是加入该点重新出现的子串的个数,但是我们这里要算的是子串,这里的子串是可以有相同的,所以我们这个点parent链上所有的节点的l[i]-l[fa[i]]的个数其实都是以该点为后缀的子串。
现在考虑k的限制,我们再上面的统计中,需要建立parent树,然后将根节点到该点路径上的值都累加到该点上。
那么我们直接将size[i]<k的点的初值直接赋值成0,其他的都赋值成l[i]-l[fa[i]]。
最后统计答案的时候,就将每个串中每个位置在后缀自动机中的对应节点的合法子串数相加即可。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#define N 200003
#define LL long long
using namespace std;
int n,m,np,nq,p,q,cnt,root,last,len,sz;
int ch[N][20],fa[N],size[N],l[N],nxt[N],a[N],now,pd[N],mark[N],v[N],pos[N];
int point[N],next[N],vi[N],tot,tt;
int head[N],nt[N];
LL c[N];
char s[N];
void add(int x,int y)
{
tot++; next[tot]=point[x]; point[x]=tot; vi[tot]=y;
}
void addfa(int x,int y)
{
tt++; nt[tt]=head[x]; head[x]=tt; v[tt]=y;
//cout<<x<<" "<<y<<endl;
}
void extend(int x)
{
int c=a[x];
p=last; np=++cnt; last=np;
l[np]=l[p]+1;
for (;p&&!ch[p][c];p=fa[p]) ch[p][c]=np;
if (!p) fa[np]=root;
else {
q=ch[p][c];
if (l[q]==l[p]+1) fa[np]=q;
else {
nq=++cnt; l[nq]=l[p]+1;
memcpy(ch[nq],ch[q],sizeof ch[nq]); size[nq]=size[q]; nxt[nq]=nxt[q];
fa[nq]=fa[q];
fa[q]=fa[np]=nq;
for (;ch[p][c]==q;p=fa[p]) ch[p][c]=nq;
}
}
add(now,np);
for (;np;np=fa[np])
if (nxt[np]!=now) {
nxt[np]=now;
size[np]++;
}
else break;
}
void dfs(int x)
{
c[x]+=c[fa[x]];
for (int i=head[x];i;i=nt[i])
dfs(v[i]);
}
int main()
{
freopen("a.in","r",stdin);
freopen("my.out","w",stdout);
scanf("%d%d",&n,&m);
root=++cnt;
for(int i=1;i<=n;i++){
scanf("%s",s+1);
last=root;
len=strlen(s+1); now=i;
for (int j=1;j<=len;j++) a[++sz]=s[j]-'a',extend(sz);
mark[i]=sz;
}
for (int i=1;i<=cnt;i++) v[l[i]]++;
for (int i=1;i<=cnt;i++) v[i]+=v[i-1];
for (int i=1;i<=cnt;i++) pos[v[l[i]]--]=i;
for (int i=1;i<=cnt;i++) {
int t=pos[i];
addfa(fa[t],t);
if (size[t]>=m) c[t]=(LL)(l[t]-l[fa[t]]);
else c[t]=0;
}
c[1]=0;
dfs(1);
for (int i=1;i<=n;i++) {
LL ans=0;
for (int j=point[i];j;j=next[j])
ans+=c[vi[j]];
printf("%I64d ",ans);
}
}