Stay Pits
Code
#include <iostream>#include<cstdio>#include<queue>#include<cstring>using namespacestd;Const intn=1000000+ +;structac_automation{#defineRoot 0Static Const intSigma_size= -; structNode {intNxt[sigma_size],sum,fa,fail; }t[n*5]; inttot; voidInsert (Charc[]) { intNow=root,len=strlen (c+1); for(intI=1; i<=len;i++) { if(t[now].nxt[c[i]-'a']==0) T[now].nxt[c[i]-'a']=++tot; now=t[now].nxt[c[i]-'a']; } t[now].sum++; } voidBuild () {Queue<int>Q; for(intI=0; i<sigma_size;i++) if(t[root].nxt[i]!=0) Q.push (T[root].nxt[i]); while(!Q.empty ()) { intnow=Q.front (); Q.pop (); for(intI=0; i<sigma_size;i++) if(t[now].nxt[i]!=0) { inttemp=T[now].fail; while(t[temp].nxt[i]==0and temp!=root) Temp=T[temp].fail; T[t[now].nxt[i]].fail=T[temp].nxt[i]; Q.push (T[now].nxt[i]); } } } intQuery (Charc[]) { intans=0, Len=strlen (c+1), now=Root; for(intI=1; i<=len;i++) { intx=c[i]-'a'; while(t[now].nxt[x]==0and Now!=root) now=T[now].fail; now=T[now].nxt[x]; inttemp=Now ; while(temp!=root) { if(t[temp].sum>=0) {ans+=t[temp].sum; T[temp].sum=-1; Temp=T[temp].fail; } Else Break; } } returnans; } #undefRoot}trie;intN;CharC[n];intMain () {scanf ("%d",&N); for(intI=1; i<=n;i++) {scanf ("%s", c+1); Trie. Insert (c); } trie. Build (); scanf ("%s", c+1); printf ("%d", Trie. Query (c)); return 0;}
[LuoguP3808] "template" AC Automaton (Simple version) array version