详细讲解
例题
模板题:
用后缀数组计算出
s
a
sa
sa 和
h
e
i
g
h
t
height
height 后,用一个单调栈就解决了。
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<stack>
using namespace std;
const int M=5e5+5;
void write(int x){
if(x<=9){
putchar(x+'0');
return;
}
write(x/10);
putchar(x%10+'0');
}
char s[M],s2[M];
int y[M],x[M],z[M],c[M],sa[M],rk[M],height[M],ans,nn;
int n,m;
void SA(){
for(int i=1;i<=n;i++) c[x[i]=s[i]]++;
for(int i=2;i<=m;i++) c[i]+=c[i-1];
for(int i=n;i>=1;i--) sa[c[x[i]]--]=i;
for(int k=1;k<=n;k<<=1){
int num=0;
for(int i=n-k+1;i<=n;i++) y[++num]=i;
for(int i=1;i<=n;i++) if(sa[i]>k) y[++num]=sa[i]-k;
for(int i=1;i<=m;i++) c[i]=0;
for(int i=1;i<=n;i++) c[x[i]]++;
for(int i=2;i<=m;i++) c[i]+=c[i-1];
for(int i=n;i>=1;i--) sa[c[x[y[i]]]--]=y[i],y[i]=0;
for(int i=1;i<=n;i++) {
z[i]=x[i];
}
num=1;x[sa[1]]=1;
for(int i=2;i<=n;i++){
x[sa[i]]=(z[sa[i]]==z[sa[i-1]]&&z[sa[i]+k]==z[sa[i-1]+k])?num:++num;
}
if(num==n) break;
m=num;
}
}
void Get_height(){
int k=0;
for(int i=1;i<=n;++i) rk[sa[i]]=i;
for(int i=1;i<=n;++i) {
if(rk[i]==1) continue;
if(k) --k;
int j=sa[rk[i]-1];
while(j+k<=n&&i+k<=n&&s[i+k]==s[j+k]) ++k;
height[rk[i]]=k;
}
}
struct Pair {
int val, pos;
};
stack<Pair> sta;
long long f[M];
int main() {
scanf("%s",s+1);
n=strlen(s+1);
m=122;
SA();
Get_height();
long long res=0;int pos=0;
for(int i=1;i<=n;i++){
int p=pos;
while(!sta.empty()&&sta.top().val>height[i]) sta.pop();
if(!sta.empty()) p=sta.top().pos;
f[i]=f[p]+(i-p)*height[i],res+=f[i];
if(height[i]==0) pos=i;
sta.push((Pair){height[i],i});
}
printf("%lld\n",(1LL)*(n-1)*n*(n+1)/2-res*2);
return 0;
}