标签:build rac new target tput modern val wan several
1 #include <stdio.h> 2 #include <iostream> 3 #include <algorithm> 4 #include <string.h> 5 #include <stdlib.h> 6 #include <math.h> 7 #include <queue> 8 #include <set> 9 10 #define INF 0x3f3f3f3f 11 #define pii pair<int,int> 12 using namespace std; 13 const int maxn = 1e6+10; 14 15 char buf[maxn]; 16 struct ac_automation{ 17 int next[maxn][26],fail[maxn],end[maxn]; 18 int root,L; 19 int newnode(){ 20 for (int i=0;i<26;i++) 21 { 22 next[L][i] = -1; 23 } 24 end[L++] = 0; 25 return L-1; 26 } 27 void init(){ 28 L = 0; 29 root = newnode(); 30 } 31 void insert(char buf[]){ 32 int len = strlen(buf); 33 int now = root; 34 for (int i=0;i<len;i++){ 35 if (next[now][buf[i]-‘a‘] == -1) 36 next[now][buf[i]-‘a‘] = newnode(); 37 now = next[now][buf[i]-‘a‘]; 38 } 39 end[now]++; 40 } 41 void build(){ 42 queue<int > Q; 43 fail[root] = root; 44 for (int i=0;i<26;i++) 45 { 46 if (next[root][i] == -1) 47 next[root][i] = root; 48 else{ 49 fail[next[root][i]] = root; 50 Q.push(next[root][i]); 51 } 52 } 53 while (!Q.empty()){ 54 int now = Q.front(); 55 Q.pop(); 56 for (int i=0;i<26;i++){ 57 if (next[now][i] == -1) 58 next[now][i] = next[fail[now]][i]; 59 else{ 60 fail[next[now][i]] = next[fail[now]][i]; 61 Q.push(next[now][i]); 62 } 63 } 64 } 65 } 66 int querry(char buf[]){ 67 int len = strlen(buf); 68 int now = root; 69 int res = 0; 70 for (int i=0;i<len;i++){ 71 now = next[now][buf[i]-‘a‘]; 72 int temp = now; 73 while (temp!=root){ 74 res += end[temp]; 75 end[temp] = 0; 76 temp = fail[temp]; 77 } 78 } 79 return res; 80 } 81 }ac; 82 83 int main(){ 84 int T; 85 scanf("%d",&T); 86 while (T--){ 87 int n; 88 scanf("%d",&n); 89 ac.init(); 90 for (int i=0;i<n;i++){ 91 scanf("%s",buf); 92 ac.insert(buf); 93 } 94 ac.build(); 95 scanf("%s",buf); 96 printf("%d\n",ac.querry(buf)); 97 } 98 return 0; 99 }
标签:build rac new target tput modern val wan several
原文地址:https://www.cnblogs.com/-Ackerman/p/11324266.html