[Bzoj4516] generating spell

Establishing a suffix automaton, and each state total len [k] -len [fa [k ]] to.

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 #define N 100005
 4 #define calc(k) (len[k]-len[fa[k]])
 5 map<int,int>ch[N<<1];
 6 int V,last,n,k,len[N<<1],sum[N<<1],fa[N<<1];
 7 long long ans;
 8 void add(int c){
 9     int p=last,np=last=++V;
10     len[np]=len[p]+1;
11     for(;(p)&&(!ch[p][c]);p=fa[p])ch[p][c]=V;
12     if (!p){
13         fa[np]=1;
14         ans+=calc(np);
15     }
16     else{
17         int q=ch[p][c];
18         if (len[q]==len[p]+1){
19             fa[np]=q;
20             ans+=calc(np);
21         }
22         else{
23             int nq=++V;
24             len[nq]=len[p]+1;
25             ch[nq]=ch[q];
26             fa[nq]=fa[q];
27             ans+=calc(nq)-calc(q);
28             fa[np]=fa[q]=nq;
29             ans+=calc(np)+calc(q);
30             for(;(p)&&(ch[p][c]==q);p=fa[p])ch[p][c]=nq;
31         }
32     }
33 }
34 int main(){
35     V=last=1;
36     scanf("%d",&n);
37     for(int i=1;i<=n;i++){
38         scanf("%d",&k);
39         add(k);
40         printf("%lld\n",ans);
41     }
42 }
View Code

 

Guess you like

Origin www.cnblogs.com/PYWBKTDA/p/11249943.html