HDU 2222 Keywords Search(AC自动机)

第一道AC自动机留念,HDU第500题留念。

学习了Just Me牛的代码风格。

#include <cstdio>
#include <queue>
#include <cstdlib>
using namespace std;
const int maxn=1e6+5;
char s[maxn];
struct Trie
{
    int count;
    Trie *fail, *next[26];
    Trie()
    {
        count=0;
        for(int i=0 ; i<26 ; i++ )
            next[i] = NULL;
        fail = NULL;
    }
};
Trie *root;
void insert(char *s)
{
    Trie *p = root;
    for(int i = 0 ; s[i] ; i++)
    {
        int id = s[i]-'a';
        if(p -> next[id] == NULL)
            p -> next[id]= new Trie();
        p = p -> next[id];
    }
    p->count++;
}
void Build_AC()
{
    queue<Trie *>q;
    q.push(root);
    while(!q.empty())
    {
        Trie *p = q.front();
        q.pop();
        for(int i = 0; i < 26 ;i++)
            if(p -> next[i] != NULL){
            if(p == root)
                p ->next[i] ->fail = root;
            else
            {
                Trie *temp = p ->fail;
                while(temp != NULL)
                {
                    if(temp -> next[i] != NULL){
                        p ->next[i] ->fail = temp ->next[i];
                        break;
                    }
                    temp=temp ->fail;
                }
                if(temp == NULL) p ->next[i] ->fail = root;
            }
            q.push(p ->next[i]);
        }
    }
}
int AC(char *s)
{
    Build_AC();
    Trie *p=root;
    int ret=0,index;
    for(int i = 0; s[i] ; i++ ){
        index = s[i]-'a';
        while(p != root && p -> next[index] == NULL)
            p = p -> fail;
        p = p -> next[index];
        if( p == NULL)
        {
            p = root;
            continue;
        }
        Trie *temp=p;
        while(temp != root && temp -> count != 0)
        {
            ret += temp -> count;
            temp -> count = 0 ;
            temp = temp -> fail;
        }
    }
    return ret;
}
void deal(Trie *T)
{
    for(int i = 0 ; i<26 ; i++)
        if(T->next[i] != NULL)
            deal(T->next[i]);
    free(T);
}
int main()
{
    int T,n;
    scanf("%d", &T);
    while( T-- )
    {
        scanf("%d",&n);
        root=new Trie();
        getchar();
        while(n--){
            scanf("%s",s);
            insert(s);
        }
        scanf("%s",s);
        printf("%d\n",AC(s));
        deal(root);
    }
    return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值