HDU 2222 Keywords Search
2013-08-19 11:03
351 查看
比较裸的AC自动机。
借鉴:http://www.cppblog.com/mythit/archive/2009/04/21/80633.html
借鉴:http://www.cppblog.com/mythit/archive/2009/04/21/80633.html
#include <cstdio> #include <cstring> #include <string> #include <iostream> #include <map> #include <set> #include <vector> #include <cmath> #include <stack> #include <queue> #include <cstdlib> #include <algorithm> using namespace std; typedef __int64 int64; typedef long long ll; #define M 500005 #define N 1000005 #define max_inf 0x7f7f7f7f #define min_inf 0x80808080 const int mod = 1e6; struct node { node *fail; node *next[26]; int cout; node() { fail = NULL; memset(next , NULL , sizeof next); cout = 0; } }*q[M]; char str ; int n; void Insert(char *str , node *rt) { int i = 0; node *p = rt; while (str[i]) { int inx = str[i]-'a'; if (!p->next[inx])p->next[inx] = new node; p = p->next[inx]; i++; } p->cout++; } void Build(node *rt) { rt->fail = NULL; int head , tail; head = tail = 0; q[tail++] = rt; while (head < tail) { int i; node *p = q[head++]; for (i = 0 ; i < 26 ; i++) { if (!p->next[i])continue; if (p == rt)p->next[i]->fail = rt; else { node *temp = p->fail; while (temp) { if (temp->next[i]) { p->next[i]->fail = temp->next[i]; break; } temp = temp->fail; } if (!temp)p->next[i]->fail = rt; } q[tail++] = p->next[i]; } } } void Solve(node *rt) { int i = 0 , ans = 0; node *p = rt; while (str[i]) { int inx = str[i]-'a'; while (!p->next[inx] && p != rt)p = p->fail; p = p->next[inx]; if (!p)p = rt; node *temp = p; while (temp != rt) { ans += temp->cout; temp->cout = 0; temp = temp->fail; } i++; } printf("%d\n",ans); } int main() { int t; scanf("%d",&t); while (t--) { char keyword[55]; node *rt = new node; scanf("%d",&n); while (n--) { scanf("%s",keyword); Insert(keyword,rt); } Build(rt); scanf("%s",str); Solve(rt); } }
相关文章推荐
- HDU-2222 Keywords Search (AC自动机入门)
- HDU 2222 Keywords Search
- hdu 2222 Keywords Search
- (字典树+AC自动机) hdu 2222 Keywords Search
- HDU 2222 Keywords Search
- Hdu2222 Keywords Search
- HDU2222-Keywords Search
- hdu 2222 Keywords Search
- Keywords Search (HDU_2222) AC自动机
- HDU 2222 Keywords Search
- Hdu 2222 . Keywords Search
- HDU2222---Keywords Search
- hdu 2222 Keywords Search (ac_automaton)
- HDU-2222 Keywords Search
- HDU 2222 Keywords Search
- HDU 2222 Keywords Search
- hdu 2222 Keywords Search (AC自动机~)
- hdu2222 Keywords Search
- HDU 2222 Keywords Search (AC自动机)
- HDU 2222 Keywords Search