标签:only script each google amp mem name math lse
C/C++:
1 #include <map> 2 #include <queue> 3 #include <cmath> 4 #include <vector> 5 #include <string> 6 #include <cstdio> 7 #include <cstring> 8 #include <climits> 9 #include <iostream> 10 #include <algorithm> 11 #define INF 0x3f3f3f3f 12 using namespace std; 13 const int MAX = 5e5 + 10, MAX_L = 1e6 + 10; 14 15 int n, t, rt; 16 char ss[MAX_L]; 17 18 struct node 19 { 20 int next[26], cnt, fail; 21 } s[MAX]; 22 23 void my_insert(char *ss) 24 { 25 int now = 0; 26 for (int i = 0; ss[i]; ++ i) 27 { 28 if (s[now].next[ss[i] - ‘a‘] == 0) 29 s[now].next[ss[i] - ‘a‘] = rt ++; 30 now = s[now].next[ss[i] - ‘a‘]; 31 } 32 s[now].cnt ++; 33 } 34 35 void getfail() 36 { 37 int now, v, temp; 38 queue <int> qu; 39 qu.push(0); 40 while (qu.size()) 41 { 42 now = qu.front(); 43 qu.pop(); 44 for (int i = 0; i < 26; ++ i) 45 { 46 if (v = s[now].next[i]) 47 { 48 if (now == 0) s[v].fail = 0; 49 else 50 { 51 temp = s[now].fail; 52 while (temp && s[temp].next[i] == 0) 53 temp = s[temp].fail; 54 s[v].fail = s[temp].next[i]; 55 } 56 qu.push(v); 57 } 58 } 59 } 60 } 61 62 int ac(char * ss) 63 { 64 int v, now = 0, sum = 0; 65 getfail(); 66 for (int i = 0; ss[i]; ++ i) 67 { 68 while (now && s[now].next[ss[i] - ‘a‘] == 0) 69 now = s[now].fail; 70 v = now = s[now].next[ss[i] - ‘a‘]; 71 while (s[v].cnt) 72 { 73 sum += s[v].cnt; 74 s[v].cnt = 0; 75 v = s[v].fail; 76 } 77 } 78 return sum; 79 } 80 81 int main() 82 { 83 scanf("%d", &t); 84 while (t --) 85 { 86 scanf("%d", &n); 87 rt = 1; 88 memset(s, 0, sizeof(s)); 89 for (int i = 0; i < n; ++ i) 90 { 91 scanf("%s", ss); 92 my_insert(ss); 93 } 94 scanf("%s", ss); 95 printf("%d\n", ac(ss)); 96 } 97 return 0; 98 }
hdu 2222 Keywords Search (AC自动机)
标签:only script each google amp mem name math lse
原文地址:https://www.cnblogs.com/GetcharZp/p/9541372.html