bzoj 2780: [Spoj]8093 Sevenk Love Oimaster(广义SAM)

时间:2023-03-09 22:55:53
bzoj 2780: [Spoj]8093 Sevenk Love Oimaster(广义SAM)

题目大意:给出n个原串,再给出m个查询串。求每个查询串出现在了多少原串中。

题解

  直接对原串建一个广义SAM,然后把每一个原串放到SAM上跑一跑,记录一下每一个状态属于多少个原串,用$size$表示。这样的话查询串直接在SAM上跑,如果失配输出0,否则直接输出记录在上面的$size$就好了。

 //minamoto
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
#define getc() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++)
char buf[<<],*p1=buf,*p2=buf;
inline int read(){
#define num ch-'0'
char ch;bool flag=;int res;
while(!isdigit(ch=getc()))
(ch=='-')&&(flag=true);
for(res=num;isdigit(ch=getc());res=res*+num);
(flag)&&(res=-res);
#undef num
return res;
}
char sr[<<],z[];int C=-,Z;
inline void Ot(){fwrite(sr,,C+,stdout),C=-;}
inline void print(int x){
if(C><<)Ot();if(x<)sr[++C]=,x=-x;
while(z[++Z]=x%+,x/=);
while(sr[++C]=z[Z],--Z);sr[++C]='\n';
}
const int N=;
int fa[N<<],ch[N<<][],sz[N<<],l[N<<],las[N<<],len[N],s[N];
int n,m,cnt=,last=,tot=;
void ins(int c){
int p=last,np=++cnt;last=np,l[np]=l[p]+;
for(;p&&!ch[p][c];p=fa[p]) ch[p][c]=np;
if(!p) fa[np]=;
else{
int q=ch[p][c];
if(l[p]+==l[q]) fa[np]=q;
else{
int nq=++cnt;l[nq]=l[p]+;
memcpy(ch[nq],ch[q],sizeof(ch[q]));
fa[nq]=fa[q];fa[q]=fa[np]=nq;
for(;ch[p][c]==q;p=fa[p]) ch[p][c]=nq;
}
}
}
inline void update(int x,int y){
for(;x&&las[x]!=y;x=fa[x])
++sz[x],las[x]=y;
}
int main(){
n=read(),m=read();
for(int i=;i<=n;++i){
last=;
char ch;
while((ch=getc())!='\n') ins(s[++tot]=ch-'a'),++len[i];
}
tot=;
for(int i=;i<=n;++i)
for(int j=,x=;j<=len[i];++j)
update(x=ch[x][s[++tot]],i);
while(m--){
tot=;
char c;bool flag=true;int x=;
while((c=getc())!='\n'&&c!=EOF){
int k=c-'a';
if(flag)
ch[x][k]?x=ch[x][k]:flag=false;
}
print(flag?sz[x]:);
}
Ot();
return ;
}