首先我们可以发现第二层函数没用,就提供了个约束的作用,对字符串没有改变的效果。又因为第一层函数对字符串的改变效果随后缀的改变而改变,且子串可以表示为后缀的前缀。因此我们就可以发现,这个本质上是在求字符串n个经函数改变后的后缀的本质不同的子串总数。
于是可以想到用广义SAM,n个字符串求子串个数,直接∑(len[i]-len[fa[i]])就行了,但是这道题n=1e5,直接暴力建广义SAM肯定会炸,于是这么考虑:从后往前扫描,对于每个i,往后找到第一个大于等于s[i]的j,然后就会提供贡献s[i,j-1],直接插到处理s[j]时last指针后头就可以了(这里可以这么理解?比如样例:dbca,就有后缀a,cc,bcc,dddd,我们再处理b的时候直接插到cc后头就行,不用再插一遍bcc),然后这块可以用单调栈维护下。
AC代码:
#include <bits/stdc++.h>
#define Re register int
#define LL long long
using namespace std;
const int N=2e6+5;
int n;char s[N];
int len;int pos[N];
struct SAM{
int cnt,fa[N],mlen[N],mp[N][26];
//fa[i]: 后缀链接
//mp[i]: 状态转移数组
SAM(){cnt=1;}//根初始化为1
inline int insert(Re ch,Re last){
if(mp[last][ch]){
Re p=last,x=mp[p][ch];
if(mlen[p]+1==mlen[x])return x;//即最初的特判1
else{
Re y=++cnt;mlen[y]=mlen[p]+1;
for(Re i=0;i<26;++i)mp[y][i]=mp[x][i];
while(p&&mp[p][ch]==x)mp[p][ch]=y,p=fa[p];
fa[y]=fa[x],fa[x]=y;
return y;//即最初的特判2
}
}
Re z=++cnt,p=last;mlen[z]=mlen[last]+1;
while(p&&!mp[p][ch])mp[p][ch]=z,p=fa[p];
if(!p)fa[z]=1;
else{
Re x=mp[p][ch];
if(mlen[p]+1==mlen[x])fa[z]=x;
else{
Re y=++cnt;mlen[y]=mlen[p]+1;
for(Re i=0;i<26;++i)mp[y][i]=mp[x][i];
while(p&&mp[p][ch]==x)mp[p][ch]=y,p=fa[p];
fa[y]=fa[x],fa[z]=fa[x]=y;
}
}
return z;
}
void solve()
{
stack<int> stk;
while(!stk.empty()) stk.pop();
pos[len+1]=1;
int last;
for(int i=len;i>=1;i--){
while(!stk.empty()&&s[stk.top()]<s[i]) stk.pop();
int k=stk.empty()?len+1:stk.top();
last=pos[k];
for(int j=i;j<k;j++) last=insert(s[i]-'a',last);
pos[i]=last;
stk.push(i);
}
LL ans=0;
for(int i=cnt;i>=1;i--) ans+=mlen[i]-mlen[fa[i]];
printf("%lld\n",ans);
}
}sam;
int main(){
scanf("%s",s+1);
len=strlen(s+1);
sam.solve();
}