您的位置:首页 > 其它

[BZOJ4566][Haoi2016]找相同字符(后缀自动机)

2017-03-30 07:44 453 查看

题目描述

传送门

题解

将两个串接在一起建立后缀自动机,中间加一个分隔符

对于自动机上的每一个点,统计其right集合中在第一个串中的数量cnt1,在第二个串中的数量cnt2

对于某一个点合法的长度是[step(pre(i))+1,step(i)]

答案累加就是cnt1*cnt2*(step(i)-step(pre(i)))

感觉这题sa是不大好做的

代码

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;
#define N 800005
#define LL long long

char s
,s2
;
int n,n2,dvd,root,last,sz,p,np,q,nq;
int ch
[30],pre
,step
,c
,pt
,cnt1
,cnt2
;
LL ans;

void extend()
{
root=last=++sz;
for (int i=0;i<n;++i)
{
int x=s[i]-'a';
p=last;np=++sz;last=np;
step[np]=step[p]+1;
while (p&&!ch[p][x])
{
ch[p][x]=np;
p=pre[p];
}
if (!p) pre[np]=root;
else
{
q=ch[p][x];
if (step[q]==step[p]+1) pre[np]=q;
else
{
nq=++sz;
step[nq]=step[p]+1;
memcpy(ch[nq],ch[q],sizeof(ch[q]));
pre[nq]=pre[q];
while (ch[p][x]==q)
{
ch[p][x]=nq;
p=pre[p];
}
pre[q]=pre[np]=nq;
}
}
}
}
int main()
{
scanf("%s",s);dvd=n=strlen(s);
s[n++]='$';
scanf("%s",s2);n2=strlen(s2);
for (int i=0;i<n2;++i) s[n++]=s2[i];
extend();
for (int i=1;i<=sz;++i) ++c[step[i]];
for (int i=1;i<=sz;++i) c[i]+=c[i-1];
for (int i=sz;i>=1;--i) pt[c[step[i]]--]=i;
p=root;
for (int i=0;i<n;++i)
{
int x=s[i]-'a';
p=ch[p][x];
if (step[p]<=dvd) ++cnt1[p];
else ++cnt2[p];
}
for (int i=sz;i>=1;--i)
{
p=pt[i];
cnt1[pre[p]]+=cnt1[p];
cnt2[pre[p]]+=cnt2[p];
}
for (int i=1;i<=sz;++i)
{
if (s[step[i]-1]=='$') continue;
ans+=(LL)cnt1[i]*cnt2[i]*(step[i]-step[pre[i]]);
}
printf("%lld\n",ans);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: