Description
给定两个字符串,求出在两个字符串中各取出一个子串使得这两个子串相同的方案数。两个方案不同当且仅当这两
个子串中有一个位置不同。
Input
两行,两个字符串s1,s2,长度分别为n1,n2。1 <=n1, n2<= 200000,字符串中只有小写字母
Output
输出一个整数表示答案
Sample Input
aabb
bbaa
Sample Output
10
题解:
据说sa也能做?但是我还是只会后缀自动机的做法。对两个串放在一起做一个广义后缀自动机,建完之后由下至上统计出每个字符串在两个串中出现的次数,答案就是所有的(o->max_len-o->parent->max_len)*(sum[0]*sum[1])
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<iomanip>
#include<cstring>
#include<string>
#include<algorithm>
#include<ctime>
#include<cmath>
using namespace std;
struct sam
{
sam *parent;
sam *son[26];
int max_len;
int siz[2];
int id;
sam(){}
void* operator new (size_t,int _,int id);
}mempool[800000];
int T;
void* sam :: operator new (size_t,int _,int id)
{
T++;
sam *o=&mempool[T];
o->id=T;
o->max_len=_;
if(id!=-1) o->siz[id]++;
return o;
}
sam* root=new(0,-1) sam,*last=root;
char s[400000];
void Insert(int zm,int id)
{
sam *p=last;
sam *np=new (p->max_len+1,id) sam;
while(p && !p->son[zm])
{
p->son[zm]=np;
p=p->parent;
}
if(!p) np->parent=root;
else
{
sam *q=p->son[zm];
if(q->max_len==p->max_len+1) np->parent=q;
else
{
sam *nq=new (p->max_len+1,-1) sam;
nq->parent=q->parent;
memcpy(nq->son,q->son,sizeof(nq->son));
q->parent=nq;
np->parent=nq;
while(p && p->son[zm]==q)
{
p->son[zm]=nq;
p=p->parent;
}
}
}
last=np;
}
struct bian
{
int l,r;
}a[1000000];
int fir[1000000];
int nex[1000000];
int tot=1;
void add_edge(int l,int r)
{
a[++tot].l=l;
a[tot].r=r;
nex[tot]=fir[l];
fir[l]=tot;
}
void get_bian()
{
for(int i=2;i<=T;i++)
add_edge(mempool[i].parent->id,mempool[i].id);
}
long long ans=0;
void dfs(int u)
{
for(int o=fir[u];o;o=nex[o])
{
dfs(a[o].r);
mempool[u].siz[0]+=mempool[a[o].r].siz[0];
mempool[u].siz[1]+=mempool[a[o].r].siz[1];
}
if(u!=1)
{
int ben=mempool[u].max_len-mempool[u].parent->max_len;
ans+=1ll*ben*mempool[u].siz[0]*mempool[u].siz[1];
}
}
int main()
{
scanf("%s",s+1);
int len=strlen(s+1);
for(int i=1;i<=len;i++) Insert(s[i]-'a',0);
last=root;
scanf("%s",s+1);
len=strlen(s+1);
for(int i=1;i<=len;i++) Insert(s[i]-'a',1);
get_bian();
dfs(1);
printf("%lld\n",ans);
return 0;
}