题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3065
题都懒得粘了…好的AC自动机模版真难找。也许是自己太水
1 #include <algorithm> 2 #include <cstdio> 3 #include <cstring> 4 #include <cstdlib> 5 #include <iostream> 6 #include <vector> 7 #include <queue> 8 #include <stack> 9 #include <map> 10 #include <string> 11 #include <climits> 12 #include <cmath> 13 14 using namespace std; 15 16 int n; 17 inline int GetId(char c) { 18 return c - 'A'; 19 } 20 21 typedef struct vir { 22 string name; 23 int freq; 24 }vir; 25 26 typedef class Node { 27 public: 28 Node *chd[26]; 29 Node *fail; 30 int id; 31 32 Node(){ 33 memset(chd, 0, sizeof(chd)); 34 fail = NULL; 35 id = -1; 36 } 37 }Node; 38 39 class AC_Automation { 40 public: 41 Node *root; 42 queue <Node*> q; 43 vir v[1005]; 44 45 AC_Automation() { 46 root = new Node; 47 while(!q.empty()) { 48 q.pop(); 49 } 50 for(int i = 0; i < n; i++) 51 v[i].freq = 0; 52 } 53 void insert(string s, int th) { 54 Node *cur = root; 55 int len = s.length(); 56 for(int i = 0; i < len; i++) { 57 int index = GetId(s[i]); 58 if(!cur->chd[index]) { 59 cur->chd[index] = new Node; 60 } 61 cur = cur->chd[index]; 62 } 63 cur->id = th; 64 v[th].name = s; 65 } 66 void BuildAC() { 67 Node *cur,*tmp; 68 q.push(root); 69 while(!q.empty()) { 70 cur = q.front(); 71 q.pop(); 72 for(int i = 0; i < 26; i++) { 73 if(cur->chd[i]) { 74 if(cur == root) { 75 cur->chd[i]->fail = root; 76 } 77 else { 78 tmp = cur->fail; 79 while(tmp->fail && !tmp->chd[i]) { 80 tmp = tmp->fail; 81 } 82 if(tmp->chd[i]) { 83 cur->chd[i]->fail = tmp->chd[i]; 84 } 85 else { 86 cur->chd[i]->fail = root; 87 } 88 } 89 q.push(cur->chd[i]); 90 } 91 } 92 } 93 } 94 void query(string s) { 95 Node *cur = root,*tmp; 96 int len = s.length(); 97 for(int i = 0; i < len; i++) { 98 int index = GetId(s[i]); 99 if(index < 0 || index >= 26) { 100 cur = root; 101 continue; 102 } 103 if(cur->chd[index]) { 104 cur = cur->chd[index]; 105 } 106 else { 107 while(cur && !cur->chd[index]) { 108 cur = cur->fail; 109 } 110 if(!cur) { 111 cur = root; 112 } 113 if(cur->chd[index]) { 114 cur = cur->chd[index]; 115 } 116 } 117 tmp = cur; 118 while(tmp->fail) { 119 if(tmp->id > -1) { 120 v[tmp->id].freq++; 121 } 122 tmp = tmp->fail; 123 124 } 125 } 126 } 127 }; 128 char pat[52], tar[2000005]; 129 130 int main() { 131 // freopen("in", "r", stdin); 132 while(scanf("%d", &n) == 1) { 133 AC_Automation ac; 134 getchar(); 135 for(int i = 0; i < n; i++) { 136 gets(pat); 137 ac.insert(pat,i); 138 } 139 ac.BuildAC(); 140 gets(tar); 141 ac.query(tar); 142 for(int i = 0; i < n; i++) { 143 if(ac.v[i].freq) { 144 cout << ac.v[i].name << ": " << ac.v[i].freq << endl; 145 } 146 } 147 } 148 }