BZOJ4516:[SDOI2016]生成魔咒(SAM)

Description

魔咒串由许多魔咒字符组成,魔咒字符可以用数字表示。例如可以将魔咒字符 1、2 拼凑起来形成一个魔咒串 [1,2]。
一个魔咒串 S 的非空字串被称为魔咒串 S 的生成魔咒。
例如 S=[1,2,1] 时,它的生成魔咒有 [1]、[2]、[1,2]、[2,1]、[1,2,1] 五种。S=[1,1,1] 时,它的生成魔咒有 [1]、
[1,1]、[1,1,1] 三种。最初 S 为空串。共进行 n 次操作,每次操作是在 S 的结尾加入一个魔咒字符。每次操作后都
需要求出,当前的魔咒串 S 共有多少种生成魔咒。

Input

第一行一个整数 n。
第二行 n 个数,第 i 个数表示第 i 次操作加入的魔咒字符。
1≤n≤100000。,用来表示魔咒字符的数字 x 满足 1≤x≤10^9

Output

输出 n 行,每行一个数。第 i 行的数表示第 i 次操作后 S 的生成魔咒数量

Sample Input

7
1 2 3 3 3 1 2

Sample Output

1
3
6
9
12
17
22

Solution

假设当前添加字符为c,原来没有c儿子而现在新增了c儿子的节点就是产生了新子串的节点
首先这些节点所代表的子串已经都是增加前S串的后缀,他们新添了一个字符c产生了新后缀
因为他们原本没有c儿子,所以这些后缀在原来的S串里没有出现过

Code

 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 #include<map>
 5 #define N (200000+1000)
 6 using namespace std;
 7 
 8 long long ans;
 9 map<int,int>Map;
10 
11 struct SAM
12 {
13     map<int,int>son[N];
14     int step[N],right[N],fa[N];
15     int last,p,q,np,nq,cnt;
16     SAM(){last=++cnt;}
17 
18     void Insert(int x)
19     {
20         p=last; np=last=++cnt; step[np]=step[p]+1; right[np]=1;
21         while (!son[p][x] && p) ans+=step[p]-step[fa[p]],son[p][x]=np,p=fa[p];
22         if (!p) fa[np]=1;
23         else
24         {
25             q=son[p][x];
26             if (step[q]==step[p]+1) fa[np]=q;
27             else
28             {
29                 nq=++cnt; step[nq]=step[p]+1;
30                 son[nq]=son[q];
31                 fa[nq]=fa[q]; fa[np]=fa[q]=nq;
32                 while (son[p][x]==q) son[p][x]=nq,p=fa[p];
33             }
34         }
35     }
36 }SAM;
37 
38 int main()
39 {
40     int n,x;
41     scanf("%d",&n);
42     for (int i=1; i<=n; ++i)
43     {
44         scanf("%d",&x);
45         SAM.Insert(x);
46         if (!Map[x]) Map[x]=1,ans++;
47         printf("%lld
",ans);
48     }
49 }
原文地址:https://www.cnblogs.com/refun/p/9355511.html