跳到正文

题解

[SDOI2016]生成魔咒 题解 SAM

Demoe约 3 分钟
原文
文章信息与版本

文章信息

发布
2021年8月6日
收录
2026年1月4日
更新
2026年11月11日
篇幅
约 3 分钟
题目
P4070

版本

  1. v1当前

题目传送门

Description\text{Description}

  • 给定一个序列,求本质不同子串个数。

  • 强制在线。

Solution\text{Solution}

考虑到本质不同子串计数,我们可以想到把序列转换成字符串来做。

不懂有没有 Hash 做法,但我没胡出来。

维护子串信息,很容易想到 SAM。

但是 xix_i 范围很大诶我们不能直接开个 2×105×1092\times 10^5\times 10^9 的数组去记录转移。

但是 SAM 有性质状态数不超过 2n−12n-1,转移数不超过 3n−43n-4。

因此直接开 map 记录就行了。

然后我们拓扑排一下直接跑出每个点 endpos\text{endpos} 等价类大小就行了。

啊这是强制在线的啊,那没事了。

考虑每次新插入一个字符的增量。

SAM 有性质每个等价类中的子串长度恰好覆盖一个整数区间。

于是每次增量即为 leni−lenlinkilen_i-len_{link_i},其中 ii 表示新加的状态。

Code\text{Code}

C++
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 ---------- //