引用大神模板
1 作者:后缀自动机·张 2 链接:https://zhuanlan.zhihu.com/p/25948077 3 来源:知乎 4 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 5 6 struct SAM{ 7 static const int maxn = 300010 * 2; 8 struct node{ 9 node*nxt[26],*fail; 10 int len; 11 }; 12 13 node*root;int cnt; 14 node no[maxn]; 15 node*newnode(){ 16 return &no[cnt++]; 17 } 18 SAM(){ 19 cnt = 0; 20 root = newnode(); 21 } 22 23 node* add(node*p,int c){ 24 node*cur = newnode(); 25 cur->len = p->len+1; 26 while(p &&!p->nxt[c])p->nxt[c] = cur,p = p->fail; 27 if(!p){ 28 cur->fail = root;return cur; 29 } 30 node*q = p->nxt[c]; 31 if(q->len == p->len+1){ 32 cur->fail = q; 33 }else{ 34 node*nq = newnode(); 35 *nq = *q; 36 nq->len = p->len+1; 37 q->fail = cur->fail = nq; 38 while(p&&p->nxt[c]==q)p->nxt[c] = nq,p = p->fail; 39 } 40 return cur; 41 } 42 43 ll getNumOfDistinctSubstrings(){ 44 auto ans = 0; 45 REP(i,1,cnt)ans+=no[i].len-no[i].fail->len; 46 return (ans); 47 } 48 };
只有不断学习才能进步!
原文:https://www.cnblogs.com/wenbao/p/6631537.html