HDU 3065 病毒侵袭持续中(AC自动机)

/* FileName: 3065.cpp Author: ACb0y Date: 2010年12月30日12:45:12 Type: AC自动机 ProblemID: HDU 3065 病毒侵袭持续中 Result: 3372006 2010-12-30 12:41:42 Accepted 3065 281MS 16760K 2218 B G++ ACb0y */ #include <iostream> #include <queue> using namespace std; struct node { node * fail; node * next[128]; int order; }; node * root; char str[1005][55]; char web[2000005]; int ans[1005]; node * get_node() { node * p = (node *)malloc(sizeof(node)); p->fail = NULL; p->order = 0; memset(p->next, NULL, sizeof(p->next)); return p; } void insert(char * str, int order) { int len = strlen(str); node * p_cur = root; for (int i = 0; i < len; ++i) { int pos = str[i] - 31; if (p_cur->next[pos] == NULL) { p_cur->next[pos] = get_node(); } p_cur = p_cur->next[pos]; } p_cur->order = order; } void build_fail() { queue<node *> q; root->fail = NULL; q.push(root); while (!q.empty()) { node * p_cur = q.front(); q.pop(); for (int i = 0; i < 128; ++i) { if (p_cur->next[i] != NULL) { if (p_cur == root) { p_cur->next[i]->fail = root; } else { node * temp = p_cur->fail; while (temp != NULL) { if (temp->next[i] != NULL) { p_cur->next[i]->fail = temp->next[i]; break; } temp = temp->fail; } if (temp == NULL) { p_cur->next[i]->fail = root; } } q.push(p_cur->next[i]); } } } } void query(char * str) { int len = strlen(str); node * p_cur = root; for (int i = 0; i < len; ++i) { int pos = str[i] - 31; while (p_cur->next[pos] == NULL && p_cur != root) { p_cur = p_cur->fail; } p_cur = p_cur->next[pos]; if (p_cur == NULL) { p_cur = root; } node * temp = p_cur; while (temp != root && temp->order != 0) { ans[temp->order]++; temp = temp->fail; } } } void clear(node * root) { for (int i = 0; i < 128; ++i) { if (root->next[i] != NULL) { clear(root->next[i]); } } free(root); } int main() { #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); #endif int n; while (scanf("%d/n", &n) != EOF) { root = get_node(); for (int i = 1; i <= n; ++i) { gets(str[i]); insert(str[i], i); } build_fail(); memset(ans, 0, sizeof(ans)); gets(web); query(web); for (int i = 1; i <= n; ++i) { if (ans[i] != 0) { printf("%s: %d/n", str[i], ans[i]); } } clear(root); } return 0; }

你可能感兴趣的:(Web,null,query,insert,Build,2010)