地址:http://acm.split.hdu.edu.cn/showproblem.php?pid=2222
题目:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 56558 Accepted Submission(s): 18493
1 #include <queue> 2 #include <cstring> 3 #include <cstdio> 4 using namespace std; 5 6 struct AC_auto 7 { 8 const static int LetterSize = 26; 9 const static int TrieSize = 26 * ( 1e5 + 50); 10 11 int tot,root,fail[TrieSize],end[TrieSize],next[TrieSize][LetterSize]; 12 13 int newnode(void) 14 { 15 memset(next[tot],-1,sizeof(next[tot])); 16 end[tot] = 0; 17 return tot++; 18 } 19 20 void init(void) 21 { 22 tot = 0; 23 root = newnode(); 24 } 25 26 int getidx(char x) 27 { 28 return x - ‘a‘; 29 } 30 31 void insert(char *ss) 32 { 33 int len = strlen(ss); 34 int now = root; 35 for(int i = 0; i < len; i++) 36 { 37 int idx = getidx(ss[i]); 38 if(next[now][idx] == -1) 39 next[now][idx] = newnode(); 40 now = next[now][idx]; 41 } 42 end[now]++; 43 } 44 45 void build(void) 46 { 47 queue<int>Q; 48 fail[root] = root; 49 for(int i = 0; i < LetterSize; i++) 50 if(next[root][i] == -1) 51 next[root][i] = root; 52 else 53 fail[next[root][i]] = root,Q.push(next[root][i]); 54 while(Q.size()) 55 { 56 int now = Q.front();Q.pop(); 57 for(int i = 0; i < LetterSize; i++) 58 if(next[now][i] == -1) next[now][i] = next[fail[now]][i]; 59 else 60 fail[next[now][i]] = next[fail[now]][i],Q.push(next[now][i]); 61 } 62 } 63 64 int match(char *ss) 65 { 66 int len,now,res; 67 len = strlen(ss),now = root,res = 0; 68 for(int i = 0; i < len; i++) 69 { 70 int idx = getidx(ss[i]); 71 int tmp = now = next[now][idx]; 72 while(tmp) 73 { 74 res += end[tmp]; 75 end[tmp] = 0;// 76 tmp = fail[tmp]; 77 } 78 } 79 return res; 80 } 81 void debug(void) 82 { 83 for(int i = 0;i < tot; i++) 84 { 85 printf("id = %3d,fail = %3d,end = %3d,chi = [",i,fail[i],end[i]); 86 for(int j = 0;j < LetterSize;j++) 87 printf("%3d",next[i][j]); 88 printf("]\n"); 89 } 90 } 91 }; 92 93 AC_auto ac; 94 char sa[1000001]; 95 int main(void) 96 { 97 int t,n; 98 scanf("%d",&t); 99 while(t--) 100 { 101 ac.init(); 102 scanf("%d",&n); 103 while(n--) 104 scanf("%s",sa),ac.insert(sa); 105 ac.build(); 106 scanf("%s",sa); 107 printf("%d\n",ac.match(sa)); 108 } 109 110 return 0; 111 }
原文:http://www.cnblogs.com/weeping/p/5937136.html