洛谷4070 BZOJ4516 SDOI2016 生成魔咒 SAM map

版权声明:本文为博主原创文章,可以转载但是必须声明版权。 https://blog.csdn.net/forever_shi/article/details/84753502

题目链接

题意:
你有 n n 次操作,每次往原串后面插入一个数,不同的数字看作不同的字符,问你每次加入一个字符之后有多少个不同的子串。n<=100000,数值范围1e9

题解:
数值范围太大,要离散化或者用个map。统计不同子串个数也算是SAM的一个经典应用了吧,SAM是可以在线回答的。

我们假设之前的答案已经统计好了,那么考虑对于每次加入的数加进SAM之后产生的新串个数。我们知道,parent树上的父节点相当于能与当前串的后缀匹配的最长的点,那么你找到插入点的parent树上的父节点,新出现的串就是那些长度在 ( l e n [ f a [ x ] ] , l e n [ x ] ] (len[fa[x]],len[x]] 的串,于是我们用这个点形成的串的长度减去它在parent树上的父节点的串长就行了。代码还是不难写的。

代码:

#include <bits/stdc++.h>
using namespace std;

int n,fa[500010],ch[500010][30],len[500010],rt=1,cnt=1,lst=1,num;
map<int,int> mp;
long long ans; 
inline void insert(int x)
{
	int cur=++cnt,pre=lst;
	lst=cur;
	len[cur]=len[pre]+1;
	for(;pre&&!ch[pre][x];pre=fa[pre])
	ch[pre][x]=cur;
	if(!pre)
	fa[cur]=rt;
	else
	{
		int ji=ch[pre][x];
		if(len[ji]==len[pre]+1)
		fa[cur]=ji;
		else
		{
			int gg=++cnt;
			memcpy(ch[gg],ch[ji],sizeof(ch[ji]));
			fa[gg]=fa[ji];
			fa[ji]=fa[cur]=gg;
			len[gg]=len[pre]+1;
			for(;pre&&ch[pre][x]==ji;pre=fa[pre])
			ch[pre][x]=gg;
		}
	}
	ans+=len[cur]-len[fa[cur]];
}
int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;++i)
	{
		int x;
		scanf("%d",&x);
		if(!mp[x])
		mp[x]=++num;
		insert(mp[x]);
		printf("%lld\n",ans);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/forever_shi/article/details/84753502