SDOI 2016 生成魔咒 题解

题目传送门

题目大意: 给出一个字符串,询问它的每一个前缀内包含多少个不同的子串。

题解

将字符一个一个加入到SAM里,每个新的字符的的贡献为 l e n ( x ) − l e n ( l i n k ( x ) ) len(x)-len(link(x)) len(x)len(link(x)),因为从 l e n ( l i n k ( x ) ) len(link(x)) len(link(x)) 这个长度开始,下面的长度的后缀都已经出现过了,只有上面的后缀是没出现过的,即新的不同的子串。

代码如下:

#include <cstdio>
#include <cstring>
#include <map>
#include <algorithm>
using namespace std;
#define maxn 200010

int n;
long long ans=0;
struct state{
	int len,link;
	map<int,int> next;
}st[maxn];
int id=0,last=0,now,p,q;
void extend(int x)
{
	now=++id;
	st[now].len=st[last].len+1;
	for(p=last;p!=-1&&!st[p].next.count(x);p=st[p].link)st[p].next[x]=now;
	if(p!=-1)
	{
		q=st[p].next[x];
		if(st[p].len+1==st[q].len)st[now].link=q;
		else
		{
			int clone=++id;
			st[clone]=st[q];st[clone].len=st[p].len+1;
			for(;p!=-1&&st[p].next[x]==q;p=st[p].link)st[p].next[x]=clone;
			st[q].link=st[now].link=clone;
		}
	}
	last=now;
}

int main()
{
	scanf("%d",&n);
	st[0].link=-1;
	for(int i=1,x;i<=n;i++)
	{
		scanf("%d",&x);
		extend(x);
		ans+=st[now].len-st[st[now].link].len;
		printf("%lld\n",ans);
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值