题目大意: 给出一个字符串,询问它的每一个前缀内包含多少个不同的子串。
题解
将字符一个一个加入到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);
}
}