hdu 2222 AC自动机 。。


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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值