hdu 2222 AC自动机 。。

来源:互联网 发布:985的学生知乎 编辑:程序博客网 时间:2024/05/16 23:49

#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 。。。

原创粉丝点击