题目:
题意:
给出一个字符串T,再给出N个字符串S,每次回答字符串S的所有循环串在T中出现次数,重复的不计入答案. 这里的循环串的意思 每次将首位字符置于末位置后形成的新串
题解:
要求出现次数很显然是需要我们建立Right集合了,这个循环串的解决方法就是把S复制两遍
有点像求公共子串的样子在自动机上奔跑,如果匹配到了就统计答案,然后如果此时匹配到的点在Parent树中的节点刚好能够表示长度为N的子串,那么直接累加贡献即可,否则沿Parent指针跳到合适的节点再累加贡献即可
这样草率的累加答案肯定会有重复的啊,我们要在累加答案的节点上打个标记,这样就不会重复累加啦
细节的话,如果你每次memset标记数组很费时间,我们可以把ta变成一个数组打标记就不用每次清空了
代码:
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int N=2000005;
int p,nq,np,last,q,cnt,fa[N],ch[N*2][30],step[N],c[N],a[N],l,r[N],flag[N];
char st[N];
void insert(int c)
{
p=last; last=np=++cnt;
step[np]=step[p]+1;
while (p && !ch[p][c]) ch[p][c]=np,p=fa[p];
if (!p){fa[np]=1; return;}
q=ch[p][c];
if (step[q]==step[p]+1){fa[np]=q;return;}
nq=++cnt; step[nq]=step[p]+1;
memcpy(ch[nq],ch[q],sizeof(ch[q]));
fa[nq]=fa[q]; fa[q]=fa[np]=nq;
while (ch[p][c]==q) ch[p][c]=nq,p=fa[p];
}
void qurry(int Q)
{
p=1;int tmp=0,ans=0;
for (int i=1;i<=l*2;i++)
{
int c=st[i]-'a';
if (ch[p][c]) p=ch[p][c],tmp++;
else
{
while (p && !ch[p][c]) p=fa[p];
if (!p) p=1,tmp=0;
else tmp=step[p]+1,p=ch[p][c];
}
if (tmp>=l)
{
int hh=p;
while (hh && !(l>step[fa[hh]] && l<=step[hh])) hh=fa[hh];//刚好能表示长度为N的子串
if (!hh) hh=1;
if (flag[hh]!=Q+1) flag[hh]=Q+1,ans+=r[hh];
}
}
printf("%d\n",ans);
}
int main()
{
scanf("%s",st+1);
l=strlen(st+1);
last=cnt=1;
for (int i=1;i<=l;i++) insert(st[i]-'a');
for (int i=1;i<=cnt;i++) c[step[i]]++;
for (int i=1;i<=cnt;i++) c[i]+=c[i-1];
for (int i=1;i<=cnt;i++) a[c[step[i]]--]=i;
p=1;
for (int i=1;i<=l;i++) p=ch[p][st[i]-'a'],r[p]++;
for (int i=cnt;i;i--) r[fa[a[i]]]+=r[a[i]];
scanf("%d",&q);
while (q--)
{
scanf("%s",st+1);
l=strlen(st+1);
for (int i=1;i<=l;i++) st[i+l]=st[i];
qurry(q);
}
}