DP(AC自动机) Keywords Search hdu222

AC自动机的算法参考:http://www.cppblog.com/mythit/archive/2009/04/21/80633.html

#include <stdio.h>
#include <string.h>
int tot;
char str[1000005];
int t;
//int time[100];
struct trie {
    trie *fail;
    trie *next[26];
    int num;
    trie() {
        for(int i=0; i<26; i++)
            next[i]=NULL;
        fail=NULL;
        num=0;
    }
}*queue[500001];
trie *root;
void build() {                         //建立字典树
    int len=strlen(str);
    trie *p=root;
    for(int i=0; i<len; i++) {
        int id=str[i]-'a';
        if(p->next[id]==NULL)
            p->next[id]=new trie();
        p=p->next[id];
    }
    p->num++;
}
void build_fail() {                   //建立失败指针,用bfs搜一遍所有的点
    int i;
    trie *u,*v;
    int fr,ed;
    fr=ed=0;
    root->fail=NULL;
    queue[ed++]=root;
    while(fr<ed)
    {
        u=queue[fr++];
        v=NULL;
        for(i=0; i<26; i++)
        {
            if(u->next[i]!=NULL)
            {
                if(u==root)
                    u->next[i]->fail=root;
                else
                {
                    v=u->fail;
                    while(v!=NULL)
                    {
                        if(v->next[i]!=NULL)
                        {
                            u->next[i]->fail=v->next[i];
                            break;
                        }
                        v=v->fail;
                    }
                    if(v==NULL)            //如果刚进入就是root,也要赋值
                        u->next[i]->fail=root;
                }
                queue[ed++]=u->next[i];
            }
        }
    }
}
int search() {                      //查找字符串
    int i=0;
    trie *p=root;
    int all=0;
    while(str[i]) {
        int id=str[i]-'a';
        while(p->next[id]==NULL&&p!=root)
            p=p->fail;
        p=p->next[id];
        p=(p==NULL)?root:p;
        trie *q=p;
        while(q!=root&&q->num!=-1) {
            all+=q->num;
            q->num=-1;                 //标记已经找过的单词
            q=q->fail;
        }
        i++;
    }
    return all;
}
int main() {
    int n;
    int i;
    int tt;
    scanf("%d",&tt);
    while(tt--) {
        scanf("%d",&n);
        tot=0;
        root=new trie();
        for(i=0; i<n; i++) {
            scanf("%s",str);
            build();
        }
        build_fail();
        scanf("%s",str);
        printf("%d\n",search());
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值