[SDOI2016]生成魔咒 题解 SAM
题目传送门
\text{Description}
-
给定一个序列,求本质不同子串个数。
-
强制在线。
\text{Solution}
考虑到本质不同子串计数,我们可以想到把序列转换成字符串来做。
不懂有没有 Hash 做法,但我没胡出来。
维护子串信息,很容易想到 SAM。
但是
但是 SAM 有性质状态数不超过
因此直接开 map 记录就行了。
然后我们拓扑排一下直接跑出每个点
啊这是强制在线的啊,那没事了。
考虑每次新插入一个字符的增量。
SAM 有性质每个等价类中的子串长度恰好覆盖一个整数区间。
于是每次增量即为
\text{Code}
const int N=2e6+5;
int n;
struct Suffix_Automaton{
int tot,lst,maxlen[N],minlen[N],link[N],siz[N],in[N];ll cntd;queue<int> q;map<int,int> to[N];
Suffix_Automaton(){tot=lst=1;}
inline void insert(int ch){
re nw=++tot,p=lst;siz[nw]=1;maxlen[nw]=maxlen[lst]+1;
while(p&&!to[p][ch]) to[p][ch]=nw,p=link[p];
if(!p) link[nw]=1;
else{
int t=to[p][ch];
if(maxlen[p]+1==maxlen[t]) link[nw]=t;
else{
int cp=++tot;maxlen[cp]=maxlen[p]+1;to[cp]=to[t];
while(p&&to[p][ch]==t) to[p][ch]=cp,p=link[p];
link[cp]=link[t];link[t]=link[nw]=cp;
}
}
lst=nw;cntd+=maxlen[nw]-maxlen[link[nw]];
}
inline void topo(){
for(re i=2;i<=tot;++i) ++in[link[i]];
for(re i=1;i<=tot;++i) if(!in[i]) q.push(i);
while(!q.empty()){
int x=q.front();q.pop();
siz[link[x]]+=siz[x];
if(!(--in[link[x]])) q.push(link[x]);
}
}
inline ll count(){
/*topo();return siz[1]-1;*/return cntd;
}// 原串不同子串个数
}SAM;
// ---------- Suffix Automaton ---------- //
int main(){
// freopen(".in","r",stdin);
// freopen(".out","w",stdout);
rd(n);
for(re i=1;i<=n;++i){int x;rd(x);SAM.insert(x);wr(SAM.count());puts("");}
return 0;
}
// ---------- Main ---------- //