巨巨博客连接
Wiki-AC自动机
B站视频详解
不知道B站视频会不会变换地址,搜”UESTCACM 每周算法讲堂 AC自动机”就有了
因为学过形式语言与自动机,把书上的每个店看成一个状态,每个fail指针看成一个转移函数就可以了
代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
| #include<bits/stdc++.h> using namespace std; #define ll long long #define MAX_N 1000006 #define MAX_Tot 500005 struct Aho{ struct state{ int next[26]; int fail,cnt; }st[MAX_Tot]; int size; queue<int>q; void init(){ while(!q.empty())q.pop(); for(int i=0;i<MAX_Tot;i++){ memset(st[i].next,0,sizeof(st[i].next)); st[i].fail=st[i].cnt=0; } size=1; } void insert(char *S){ int n=strlen(S); int now=0; for(int i=0;i<n;i++){ int c=S[i]-'a'; if(!st[now].next[c])st[now].next[c]=size++; now=st[now].next[c]; } st[now].cnt++; } void build(){ st[0].fail=-1; q.push(0); while(!q.empty()){ int u=q.front();q.pop(); for(int i=0;i<26;i++){ if(st[u].next[i]){ if(u==0)st[st[u].next[i]].fail=0; else{ int v= st[u].fail; while(v!=-1){ if(st[v].next[i]) { st[st[u].next[i]].fail=st[v].next[i]; break; } v=st[v].fail; } if(v==-1)st[st[u].next[i]].fail=0; } q.push(st[u].next[i]); } } } } int Get(int u){ int res=0; while(u&&st[u].cnt!=-1){ res=res+st[u].cnt; st[u].cnt=-1; u=st[u].fail; } return res; } int match(char *S){ int n=strlen(S); int res=0,now=0; for(int i=0;i<n;i++){ int c = S[i]-'a'; if(st[now].next[c]){ now = st[now].next[c]; } else{ int p = st[now].fail; while(p!=-1&&st[p].next[c]==0){ p=st[p].fail; } if(p==-1)now=0; else now = st[p].next[c]; } if(st[now].cnt){ res=res+Get(now); } } return res; } }aho; char S[MAX_N]; int main(){ int t; scanf("%d",&t); while(t--){ aho.init(); int m; scanf("%d",&m); while(m--){ scanf("%s",S); aho.insert(S); } scanf("%s",S); aho.build(); printf("%d\n",aho.match(S)); } }
|