Description
题解:
哈哈这道题自己YY出来了很开心(不过OZY大神告诉我与LCA有关)。最长公共前缀稍微想想都觉得很难搞,毕竟是后缀自动机,所以把原字符串反过来建,然后变成了求最长公共后缀。对于两个后缀,若他们在后缀自动机上对应的节点分别为 x x 和,那么他们的最长公共后缀长度就是 mx[lca(x,y)] m x [ l c a ( x , y ) ] (这里的lca指的是parent树上的),这个也很好懂,因为公共,所以 right r i g h t 集合肯定一样,所以就是lca,然后最长,那就是最长长度了。然后再求出每个节点是多少对后缀对应的点的lca即可,这个随便搞,我用的是容斥。
代码:
#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define pa pair<int,int>
const int Maxn=1000010;
const int inf=2147483647;
int tot=1,last=1;
int mx[Maxn],par[Maxn],son[Maxn][26];
LL f[Maxn],ans=0;
void extend(int x)
{
int p=last,np=++tot;mx[np]=mx[p]+1;f[np]=1;
while(p&&!son[p][x])son[p][x]=np,p=par[p];
if(!p)par[np]=1;
else
{
int q=son[p][x];
if(mx[p]+1==mx[q])par[np]=q;
else
{
int nq=++tot;mx[nq]=mx[p]+1;
for(int i=0;i<26;i++)son[nq][i]=son[q][i];
par[nq]=par[q];
par[q]=par[np]=nq;
while(son[p][x]==q)son[p][x]=nq,p=par[p];
}
}last=np;
}
char s[Maxn];
struct Edge{int y,next;}e[Maxn];
int Last[Maxn],Len=0;
void ins(int x,int y){int t=++Len;e[t].y=y;e[t].next=Last[x];Last[x]=t;}
void dfs(int x)
{
bool flag=true;LL t1,t2=0;
for(int i=Last[x];i;i=e[i].next)
{
flag=false;
int y=e[i].y;
dfs(y);f[x]+=f[y];t2+=(f[y]*(f[y]-1LL)/2LL);
}
if(!flag)
{
t1=f[x]*(f[x]-1LL)/2LL-t2;
t1*=(mx[x]*2LL);
ans-=t1;
}
}
int main()
{
scanf("%s",s);
int ls=strlen(s);
for(int i=ls-1;i>=0;i--)extend(s[i]-'a');
for(int i=2;i<=tot;i++)ins(par[i],i);
LL t=1;
for(LL j=2;j<=ls;j++)ans+=(j*(j-1)+t),t+=j;
dfs(1);
printf("%lld",ans);
}