HDU 2222
2017-08-24 10:34
141 查看
题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=2222题解:
AC自动4000
机模板题
代码:
#include <cmath> #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; #define met(a,b) memset(a,b,sizeof(a)) #define inf 0x3f3f3f3f const int maxn1=1e6+10; const int maxn2=1e4+10; char keyword[maxn2]; char s[maxn1]; struct node { int cnt; node *next[26],*fail; node() { cnt=0; fail=NULL; for(int i=0;i<26;i++) next[i]=0; } }*root; //构建字典树 void insert(char *s,node *p) { int i=0,k; while(s[i]) { k=s[i++]-'a'; if(p->next[k]==NULL) p->next[k]=new node(); p=p->next[k]; } p->cnt++; } node *q[maxn1]; //构建fail指针 void build(node *root) { int head=0,tail=1; q[head]=root; node *temp,*p; while(head<tail) { temp=q[head++]; // 查找当前节点的子节点 for(int i=0;i<26;i++) { if(temp->next[i]) { if(temp==root) // 当这个子节点是ROOT的子节点时,它的fail指针就是ROOT temp->next[i]->fail=root; else { p=temp->fail; // 指向这个子节点的父亲节点fail指针 while(p) { // 查找这个子节点的父亲节点fail指针的节点的子节点,看看有没有出现过这个子节点 if(p->next[i]) // 有的话,直接指过去 { temp->next[i]->fail=p->next[i]; break; } // 没有的话,就继续找 p=p->fail; } if(!p) // 没有找到,那么就把这个节点的fail指针指向ROOT temp->next[i]->fail=root; } q[tail++]=temp->next[i]; } } } } //查询 int query(char *s,node *root) { int ans=0,len=strlen(s),k; node *p=root; for(int i=0;i<len;i++) { k=s[i]-'a'; // 如果找不到,就进行fail指针去寻找 while(!p->next[k]&&p!=root) p=p->fail; p=p->next[k]; if(!p) p=root; node *temp=p; while(temp!=root&&temp->cnt!=-1) { ans+=temp->cnt; // 如果匹配了,那么就加上这个点上的CNT值 temp->cnt=-1; // 将找过的标记一下 temp=temp->fail; } } return ans; } //多次进行,初始化 void del(node *root) { if(root==NULL) return; for(int i=0;i<26;i++) del(root->next[i]); delete (root); } int main() { int t; scanf("%d",&t); while(t--) { root = new node(); int n; scanf("%d",&n); for(int i=0;i<n;i++) { scanf("%s",keyword); insert(keyword,root); } build(root); scanf("%s",s); printf("%d\n",query(s,root)); del(root); } }
相关文章推荐
- hdu 2222 AC自动机模板题(指针版+数组版)
- HDU2222---Keywords Search
- HDU 2222 Keywords Search 【AC自动机模板】
- hdu 2222 Keywords Search
- hdu 2222 Keywords Search ac自己主动机
- hdu 2222 Keywords Search (ac自动机)
- HDU-2222 Keywords Search AC自动机
- HDU 2222 ACAM模板(AC自动机)
- hdu 2222 Keywords Search (ac自动机入门题)
- HDU 2222 Keywords Search(AC自动机模板)
- HDU 2222 Keywords Search (AC自动机模版题)
- HDU 2222
- hdu 2222(AC自动机)
- HDU 2222 Keywords Search AC自动机
- HDU 2222 Keywords Search
- HDU 2222 Keywords Search (AC自动机)
- hdU 2222 Keywords Search(AC自动机)
- hdu2222之AC自动机入门
- hdu 2222 AC自动机
- HDU 2222 Keywords Search (AC自动机模板题)