hdu 2222 AC自动机 。。
2012-12-01 16:25
288 查看
#include <cstdio> #include <cstring> #include <iostream> #include <queue> using namespace std; const int MAXK = 26; const int MAXN = 500010 ; const int A = 'a'; struct node { node * fail ; node * next[MAXK]; int count ; node(){ fail = NULL; count = 0; for(int i=0 ;i<26;i++){ next[i] = NULL; } } }; char keyword[51]; char str[1000010]; void insert(char *str, node *root){ node *p =root ; int i= 0 ,index ; while(str[i]){ index = str[i] - 'a' ; if(p->next[index]==NULL){ p->next[index] = new node; } p = p->next[index]; i++; } p->count++; } queue<node *>q; void build_ac_automation(node *root){ while(!q.empty()) q.pop(); q.push(root); while(!q.empty()){ node *top = q.front(); q.pop(); node *p ; for(int i=0 ;i<26;i++){ if(top->next[i]){ if(top == root) { top->next[i]->fail=root; q.push(top->next[i]); continue; } p = top->fail; while(p){ if(p->next[i]){ top->next[i]->fail = p->next[i]; break; }else{ p = p->fail; } } if(p ==NULL){ top ->next[i]->fail = root; } q.push(top->next[i]); } } } } int query(node *root){ int cnt = 0 ; int len = strlen(str); node *p = root; for(int i=0;i<len ;i++){ int idx = str[i] - 'a'; while(!p->next[idx]&&p!=root){ p = p->fail; } p = p->next[idx]; p = (p== NULL) ? root:p; node *tmp = p; while(tmp!=root&& tmp->count != -1){ cnt += tmp ->count ; tmp -> count = -1 ; tmp = tmp->fail; } } return cnt; } int main(){ int cas ; scanf("%d",&cas); while(cas -- ){ node *root = new node ; int n ; scanf("%d",&n); for(int i=1;i<=n;i++){ scanf("%s",keyword); insert(keyword,root); } build_ac_automation(root); scanf("%s",str); int ans = query(root); cout <<ans <<endl; } return 0; }
AC自动机的水题。。 多组数据 每一组数据 都要重新建树 ,但没有把以前的delete 。 愚钝 不会 delete 。。。
相关文章推荐
- HDU 2222 Keywords Search [AC自动机]
- AC自动机 - 多模式串匹配问题的基本运用 + 模板题 --- HDU 2222
- |Hdu 2222|AC自动机|Keywords Search
- HDU 2222 AC自动机 入门题
- hdu_2222_Keywords Search(AC自动机板子)
- HDU2222 AC自动机入门
- Keywords Search - HDU 2222 AC自动机
- HDU 2222 AC自动机 解题报告
- hdu 2222 Keywords Search(AC自动机模板)
- HDU 2222 AC自动机模版题
- HDU 2222 Keywords Search(AC自动机模板)
- Ac自动机_hdu_2222_Keywords Search
- hdu 2222 ac自动机模板题
- hdu 2222 AC自动机(可做模板)
- hdu_2222_Keywords Search(AC自动机板子)
- AC自动机算法(hdu-2222)
- 【AC自动机详解+入门模板】HDU 2222
- hdu 2222 keywords search (AC自动机 模板)
- HDU 2222 AC自动机
- Keywords Search - HDU 2222(AC自动机模板)