题目:
题解:
又有点像当时找公共子串的时候了,这个位置不同的也可以一定要扯上right集了
对第一个串建立后缀自动机,然后用第二个串在自动机上进行匹配
sum表示的是当前状态之前fa链上点的总贡献。因为如果匹配到当前的状态,那么fa链上之前的就都被匹配上了。
sum[i]=sum[fa[i]]+(l[fa[i]]−l[fa[fa[i]]])∗right[fa[i]] s u m [ i ] = s u m [ f a [ i ] ] + ( l [ f a [ i ] ] − l [ f a [ f a [ i ] ] ] ) ∗ r i g h t [ f a [ i ] ]
进行匹配的时候匹配到一个节点的贡献为 sum[p]+(tmp−l[fa[p]])∗right[p] s u m [ p ] + ( t m p − l [ f a [ p ] ] ) ∗ r i g h t [ p ]
代码:
#include <cstdio>
#include <cstring>
#define LL long long
using namespace std;
const int N=400005;
int p,np,last,q,nq,cnt,step[N],ch[N*2][30],fa[N],r[N],c[N],a[N];
LL ans,sum[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 calc()
{
scanf("%s",st+1);
p=1;int tmp=0;
int l=strlen(st+1);
for (int i=1;i<=l;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) tmp=0,p=1;
else tmp=step[p]+1,p=ch[p][c];
}
ans+=sum[p]+(LL)(tmp-step[fa[p]])*(LL)r[p];
}
}
int main()
{
scanf("%s",st+1);
last=cnt=1;
int l=strlen(st+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]];
for (int i=1;i<=cnt;i++) sum[a[i]]=sum[fa[a[i]]]+(LL)(step[fa[a[i]]]-step[fa[fa[a[i]]]])*(LL)r[fa[a[i]]];
calc();
printf("%lld",ans);
}