hdu 2222

Ac自动机模板题

#include <cstdio>
#include <cstring>
#include <iostream>
#include <time.h>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
typedef long long  ll;
using namespace std;
struct node{
   node *fail;
   node *next[26];
   int cnt;
   node(){
    fail = NULL;
    cnt = 0;
    memset(next,NULL,sizeof(next));
   }
}*q[500010];
char str[60];
char s[1000010];
void Insert(node *root){
    node *p = root;
    for(int i = 0;str[i];i++){
        int num = str[i] - 'a';
        if(p->next[num] == NULL) p->next[num] = new node();
        p = p->next[num];
    }
    p->cnt++;
}
void Build_Ac(node *root){
    int head = 0,tail = 0;
    root->fail = NULL;
    q[head++] = root;
    while(head != tail){
        node *temp = q[tail++];
        node *p = NULL;
        for(int i = 0;i < 26;i++){
            if(temp->next[i] != NULL){
                if(temp == root) temp->next[i]->fail = root;
                else{
                    p = temp->fail;
                    while(p != NULL){
                        if(p->next[i] != NULL){
                            temp->next[i]->fail = p->next[i];
                            break;
                        }
                        p = p->fail;
                    }
                    if(p == NULL) temp ->next[i]->fail = root;
                }
                q[head++] = temp->next[i];
            }
        }
    }
}
int Query(node *root){
    int cnt = 0,l = strlen(s);
    node *p = root;
    for(int i = 0;s[i];i++){
        int num = s[i] - 'a';
        while(p->next[num] == NULL && p != root) p=p->fail;
        p = p->next[num];
        if(p == NULL) p = root;
        else p = p;
        node *temp = p;
        while(temp != root && temp->cnt != -1 ){
            cnt += temp->cnt;
            temp->cnt = -1;
            temp = temp->fail;
        }
    }
    return cnt;
}
int main(){
    int t;
    while(~scanf("%d",&t)){
        while(t--){
            int n;
            scanf("%d",&n);
            node *root = new node();
            for(int i = 0;i < n;i++){
                scanf("%s",str);
                Insert(root);
            }
            Build_Ac(root);
            scanf("%s",s);
            int num = Query(root);
            printf("%d\n",num);
        }
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值