字典树+KMP
参考自: http://www.cppblog.com/mythit/archive/2009/04/21/80633.html
1 const int MAXN = 26; //字典大小 2 3 //定义结点 4 struct node{ 5 node* fail; 6 node* child[MAXN]; 7 int count; 8 node(){ 9 fail = NULL; 10 count = 0; 11 memset(child, NULL, sizeof(child)); 12 } 13 }; 14 15 //将词插入字典树 16 void insert(node* root, char* str){ 17 node* p = root; 18 int i = 0; 19 while(str[i]){ 20 int index = str[i] - 'a'; 21 if(p->child[index] == NULL) p->child[index] = new node(); 22 p = p->child[index]; 23 ++i; 24 } 25 p->count++; 26 } 27 28 //BFS构造失配指针/构建ACautomation 29 //由当前结点构造子结点失配指针 30 void build_acautomation(node* root){ 31 queue<node*> q; 32 root->fail = NULL; 33 q.push(root); 34 while(!q.empty()){ 35 node* temp = q.front(); 36 node* p = NULL; 37 for(int i = 0; i < MAXN; ++i){ 38 if(temp->child[i] != NULL){ 39 if(temp == root) temp->child[i]->fail = root; 40 else{ 41 p = temp->fail; 42 while(p != NULL){ 43 if(p->child[i] != NULL){ 44 temp->child[i]->fail = p->child[i]; 45 break; 46 } 47 p = p->fail; 48 } 49 if(p == NULL) temp->child[i]->fail = root; 50 } 51 q.push(temp->child[i]); 52 } 53 } 54 } 55 } 56 57 //ACautomation匹配 58 //计算当前进行匹配的字符串及其后缀子串的个数 59 //count因题而异 60 int query(node* root){ 61 int i = 0, cnt = 0, index; 62 node* p = root; 63 while(str[i]){ 64 index = str[i]-'a'; 65 while(p->child[index] == NULL && p != root) p = p->fail; 66 p = p->child[index]; 67 p = (p == NULL ? root : p); 68 node* temp = p; 69 while(temp != root && temp->count != -1){ 70 cnt += temp->count; 71 temp->count = -1; 72 temp = temp->fail; 73 } 74 ++i; 75 } 76 return cnt; 77 }
继续学习..........准备做题(VJ kuangbin AC自动机专题)