# [BZOJ3238][AHOI2013]差异（后缀数组+单调栈）

## 题解

$O\left({n}^{2}\right)$$O(n^2)$

n的范围无法承受
$O\left(Nlo{g}_{2}N\right)$$O(Nlog_2N)$

## 代码

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
#define ll long long
const int maxn=1e6;
const int inf=1e9;

int n,m=200;
int x[maxn],y[maxn],c[maxn],sa[maxn],rnk[maxn],height[maxn];
char s[maxn];
ll ans;

void build_sa()
{
for (int i=0; i<m; i++) c[i]=0;
for (int i=0; i<n; i++) c[x[i]=s[i]]++;
for (int i=1; i<m; i++) c[i]+=c[i-1];
for (int i=n-1; i>=0; i--) sa[--c[x[i]]]=i;

for (int k=1; k<=n; k<<=1)
{
int p=0;
for (int i=n-k; i<n; i++) y[p++]=i;
for (int i=0; i<n; i++) if (sa[i]>=k) y[p++]=sa[i]-k;

for (int i=0; i<m; i++) c[i]=0;
for (int i=0; i<n; i++) c[x[i]]++;
for (int i=1; i<m; i++) c[i]+=c[i-1];
for (int i=n-1; i>=0; i--) sa[--c[x[y[i]]]]=y[i];

swap(x,y);
p=1; x[sa[0]]=0;
for (int i=0; i<n; i++)
x[sa[i]] = y[sa[i-1]]==y[sa[i]] && ((sa[i-1]+k>=n?-1:y[sa[i-1]+k])==(sa[i]+k>=n?-1:y[sa[i]+k]))? p-1:p++;
if (p>n) break;
m=p;
}
}

void build_height()
{
for (int i=0; i<n; i++) rnk[sa[i]]=i;
int k=0; height[0]=0;
for (int i=0; i<n; i++)
{
if (!rnk[i]) continue;
if (k) k--;
int j=sa[rnk[i]-1];
while (i+k<n && j+k<n && s[i+k]==s[j+k]) k++;
height[rnk[i]]=k;
}
}

int zhan[maxn],lp[maxn],rp[maxn],top;
void findlcp()
{
for (int i=n; i>=1; i--) height[i]=height[i-1];
zhan[0]=1;//维护一个单调上升的栈
for (int i=2; i<=n; i++)
{
while (top && height[zhan[top]]>=height[i]) top--;
lp[i]=i-zhan[top]; zhan[++top]=i;
}
zhan[0]=n+1; top=0;
for (int i=n; i>=2; i--)
{
while (top && height[zhan[top]]>height[i]) top--;
rp[i]=zhan[top]-i; zhan[++top]=i;
}

for (int i=2; i<=n; i++) ans+= (ll) 2*lp[i]*rp[i]*height[i];
}

int main()
{
scanf("%s",s);
n=strlen(s);
build_sa();
build_height();

findlcp();
printf("%lld\n",(ll) n*(n-1)*(n+1)/2-ans);
}