3 aaa bbb ccc 2 aaabbbccc bbaacc
web 1: 1 2 3 total: 1
#include <cstdio> #include <cstring> #include <queue> #include <algorithm> using namespace std; int const MAX = 1e4 + 5; int ans[MAX], num; char word[205], text[MAX]; struct node { int id; bool end; node *next[96]; node *fail; node() { id = 0; end = false; memset(next, NULL, sizeof(next)); fail = NULL; } }; void Insert(node *p, char *s, int id) { for(int i = 0; s[i] != '\0'; i++) { int idx = s[i] - 32; if(p -> next[idx] == NULL) p -> next[idx] = new node(); p = p -> next[idx]; } p -> end = true; p -> id = id; } void AC_Automation(node *root) { queue <node*> q; q.push(root); while(!q.empty()) { node *p = q.front(); q.pop(); for(int i = 0; i < 96; i++) { if(p -> next[i]) { if(p == root) p -> next[i] -> fail = root; else p -> next[i] -> fail = p -> fail -> next[i]; q.push(p -> next[i]); } else { if(p == root) p -> next[i] = root; else p -> next[i] = p -> fail -> next[i]; } } } } bool Query(node *root) { bool flag = false; num = 0; int cnt = 0, len = strlen(text); node *p = root; for(int i = 0; i < len; i++) { if(num == 3) break; int idx = text[i] - 32; while(!p -> next[idx] && p != root) p = p -> fail; p = p -> next[idx]; if(!p) { p = root; continue; } node *tmp = p; while(tmp != root) { if(tmp -> end) { flag = true; ans[num++] = tmp -> id; break; } tmp = tmp -> fail; } } return flag; } int main() { int n, m, tot = 0; scanf("%d", &n); getchar(); node *root = new node(); for(int i = 1; i <= n; i++) { gets(word); Insert(root, word, i); } AC_Automation(root); scanf("%d", &m); getchar(); for(int i = 1; i <= m; i++) { gets(text); if(Query(root)) { tot++; printf("web %d:", i); sort(ans, ans + num); for(int j = 0; j < num; j++) printf(" %d", ans[j]); printf("\n"); } } printf("total: %d\n", tot); }
原文地址:http://blog.csdn.net/tc_to_top/article/details/44097747