Codeforces #235 C.Cyclical Quest(后缀自动机)

传送门

题意:给定一个模式串和nn个匹配串,询问原串有多少个子串和匹配串循环同构


考虑要求循环同构,于是先对SS建出后缀自动机
把每次询问的XX倍长在自动机上跑

如果当前匹配的长度已经超过原串长时跳failfail到原串应该的位置上
注意自动机上每个点的贡献只记一次

#include<bits/stdc++.h>
using namespace std;
const int RLEN=1<<21|1;
inline char gc(){
    static char ibuf[RLEN],*ib,*ob;
    (ib==ob)&&(ob=(ib=ibuf)+fread(ibuf,1,RLEN,stdin));
    return (ib==ob)?EOF:*ib++;
} 
#define gc getchar
inline int read(){
    char ch=gc();
    int res=0,f=1;
    while(!isdigit(ch))f^=ch=='-',ch=gc();
    while(isdigit(ch))res=(res+(res<<2)<<1)+(ch^48),ch=gc();
    return f?res:-res;
}
#define ll long long
#define pii pair<int,int>
#define fi first
#define se second
#define pb push_back
#define pob pop_back
#define pf push_front
#define pof pop_front
#define mp make_pair
#define bg begin
#define re register
const int N=2000005;
int nxt[N][26],fa[N],siz[N],len[N],A[N],rk[N],vis[N];
int last,tot;
inline void insert(int c){
	int cur=++tot,p=last;last=cur,len[cur]=len[p]+1,siz[cur]=1;
	for(;p&&!nxt[p][c];p=fa[p])nxt[p][c]=cur;
	if(!p)fa[cur]=1;
	else{
		int q=nxt[p][c];
		if(len[p]+1==len[q])fa[cur]=q;
		else{
			int clo=++tot;
			memcpy(nxt[clo],nxt[q],sizeof(nxt[q]));
			fa[clo]=fa[q],fa[q]=fa[cur]=clo;
			len[clo]=len[p]+1;
			for(;p&&nxt[p][c]==q;p=fa[p])nxt[p][c]=clo;
		}
	}
}
inline void build(){
	for(int i=1;i<=tot;i++)A[len[i]]++;
	for(int i=1;i<=tot;i++)A[i]+=A[i-1];
	for(int i=tot;i;i--)rk[A[len[i]]--]=i;
	for(int i=tot;i;i--)siz[fa[rk[i]]]+=siz[rk[i]];
}
inline int calc(char *s,int n,int t){
	int p=1,l=0,res=0;
	for(int i=1;i<=n*2-1;i++){
		int c=s[i]-'a';
		while(p!=1&&!nxt[p][c])p=fa[p],l=len[p];
		if(nxt[p][c])p=nxt[p][c],l++;
		while(len[fa[p]]>=n)p=fa[p],l=len[p];
		if(l>=n&&vis[p]!=t)vis[p]=t,res+=siz[p];
	}return res;
}
int n,q;
char s[N];
int main(){
	scanf("%s",s+1);
	n=strlen(s+1);
	last=tot=1;
	for(int i=1;i<=n;i++)insert(s[i]-'a');
	build();
	n=read();
	for(int i=1;i<=n;i++){
		scanf("%s",s+1);
		int len=strlen(s+1);
		for(int i=1;i<len;i++)
			s[i+len]=s[i];
		cout<<calc(s,len,i)<<'\n';
	}
}
posted @ 2019-07-05 16:48  Stargazer_cykoi  阅读(159)  评论(0编辑  收藏  举报