Count New String(广义SAM)
顽强补题,刚刚学广义后缀自动机 ,貌似就是 的多文本串形式。
不过用
加修改
结点也可以实现广义
,大概就是碰到新的串就将
置为
。好了开始讲题(口胡)。
貌似这个题意很迷惑,大概就是给定 两个区间 ,进行两次 转换操作,求所有本质不同的子串个数。
考虑外层 比 大,所以内层 变换相当于没有,因为还要被再变换一次。
考虑到所有子串都可以转换为后缀的前缀形式。
所以答案变为: 的本质不同的子串。
首先我们肯定不能暴力建图跑 ,这样空间必然炸。
考虑字符集大小 。
所以后缀的形式最坏是:
即最多 。
因此考虑进行从后往前遍历当前字符 向右查找第一个 的位置 。
这里的向右查找操作可以用单调栈实现。
然后 的子串就会产生新的贡献,因为 的字符都会 被更新。
然后每次插入 的子串跑 即可。
貌似
和序列自动机也能搞,但是我太菜了。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=2e6+5,M=2e4+5,inf=0x3f3f3f3f,mod=1e9+7;
#define mst(a) memset(a,0,sizeof a)
#define lx x<<1
#define rx x<<1|1
#define reg register
#define PII pair<int,int>
#define fi first
#define se second
#define pb push_back
char s[N];
int pos[N],n;
struct SAM{
int last,cnt;int ch[N<<1][26],fa[N<<1],len[N<<1],sz[N];
void insert(int c){
int p=last,np=++cnt;last=np;len[np]=len[p]+1;
for(;p&&!ch[p][c];p=fa[p]) ch[p][c]=np;
if(!p) fa[np]=1;
else {
int q=ch[p][c];
if(len[q]==len[p]+1) fa[np]=q;
else {
int nq=++cnt;len[nq]=len[p]+1;
memcpy(ch[nq],ch[q],sizeof ch[q]);
fa[nq]=fa[q],fa[q]=fa[np]=nq;
for(;ch[p][c]==q;p=fa[p]) ch[p][c]=nq;
}
}
sz[np]=1;
}
void build(){
scanf("%s",s+1); n=strlen(s+1);
last=cnt=1;
}
void solve(){
pos[n+1]=1;
stack<int> st;
for(int i=n;i>=1;i--){
while(!st.empty()&&s[st.top()]<s[i]) st.pop();
int k = st.empty() ? n + 1 : st.top();
last=pos[k];
for(int j=i;j<k;j++) insert(s[i]-'a');
pos[i]=last;
st.push(i);
}
ll ans = 0;
for(int i=2;i<=cnt;i++) ans+=len[i]-len[fa[i]];
printf("%lld\n",ans);
}
}sam;
int main(){
sam.build();
sam.solve();
return 0;
}