1. 程式人生 > >4516. [SDOI2016]生成魔咒【後綴自動機】

4516. [SDOI2016]生成魔咒【後綴自動機】

sdoi ace 字串 right 三種 esp oid n) 自動

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
假設當前添加字符為c,原來沒有c兒子而現在新增了c兒子的節點就是產生了新子串的節點
首先這些節點所代表的子串已經都是增加前S串的後綴,他們新添了一個字符c產生了新後綴
因為他們原本沒有c兒子,所以這些後綴在原來的S串裏沒有出現過
 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\n",ans); 48 } 49 }

4516. [SDOI2016]生成魔咒【後綴自動機】