题意
给定两个字符串,求出在两个字符串中各取出一个子串使得这两个子串相同的方案数。两个方案不同当且仅当这两个子串中有一个位置不同。
1 <=n1, n2<= 200000
分析
一眼就想到了用sam,显然一个建一个跑,只是没那么快想到具体怎么做而已。。。
可以预处理处每个点的right集大小,设为f[i],然后把第二个串在sam上面跑。
若跑到一个节点,设当前长度为len,节点的合法长度区间为[mn,mx],那么这个节点对答案的贡献就要加上
f[i]∗len∗(len−mn+1)
还注意到若跑到了节点x,那么x的所有父亲的答案的贡献的系数都要+1,那么就记录一下,跑完之后做一次前缀和,然后再统计每个节点对答案的贡献即可。
代码
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long LL;
const int N=400005;
int cnt,last,mx[N],f[N],ch[N][26],app[N],fa[N],b[N],c[N];
char s[N];
LL ans;
void ins(int x)
{
int p,q,np,nq;
p=last;last=np=++cnt;mx[np]=mx[p]+1;f[np]=1;
for (;!ch[p][x]&&p;p=fa[p]) ch[p][x]=np;
if (!p) fa[np]=1;
else
{
q=ch[p][x];
if (mx[q]==mx[p]+1) fa[np]=q;
else
{
nq=++cnt;mx[nq]=mx[p]+1;
memcpy(ch[nq],ch[q],sizeof(ch[q]));
fa[nq]=fa[q];
fa[q]=fa[np]=nq;
for (;ch[p][x]==q;p=fa[p]) ch[p][x]=nq;
}
}
}
void prework(int n)
{
for (int i=1;i<=cnt;i++) b[mx[i]]++;
for (int i=1;i<=n;i++) b[i]+=b[i-1];
for (int i=1;i<=cnt;i++) c[b[mx[i]]--]=i;
for (int i=cnt;i>=1;i--) f[fa[c[i]]]+=f[c[i]];
}
void solve(int n)
{
int now=1,len=0;
for (int i=0;i<n;i++)
{
int u=s[i]-'a';
if (ch[now][u]) now=ch[now][u],len++;
else
{
for (;!ch[now][u]&&now;now=fa[now]);
if (!now) now=1,len=0;
else
{
len=mx[now]+1;
now=ch[now][u];
}
}
ans+=(LL)f[now]*(len-mx[fa[now]]);app[fa[now]]++;
}
for (int i=cnt;i>=1;i--) app[fa[c[i]]]+=app[c[i]],ans+=(LL)app[c[i]]*f[c[i]]*(mx[c[i]]-mx[fa[c[i]]]);
}
int main()
{
scanf("%s",s);
int len=strlen(s);
last=cnt=1;
for (int i=0;i<len;i++) ins(s[i]-'a');
prework(len);
scanf("%s",s);
len=strlen(s);
solve(len);
printf("%lld",ans);
return 0;
}