HDU 2222  Keywords Search(AC自…

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2222

 

分析见大牛:http://www.cppblog.com/mythit/archive/2009/07/30/80633.html

 

模版见大神:http://archive.cnblogs.com/a/2206679/

这个模版貌似废话比较多,其实可以更简略的~ ~ ~

 

附上自己的代码:

 

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define N 500008

typedef struct point{
   int count;
   struct point *next[26],*fail;
}*Tree,Node;
Tree root;

char str[1000008];
Tree Q[500008];

Tree NEW()
{
   int i;
   Tree p;
   p=(Tree)malloc(sizeof(Node));
   for(i=0;i<26;i++)
       p->next[i]=NULL;
   p->count=0;
   p->fail=NULL;
   return p;
}

void Build(char ss[])
{
   int i=0;
   Tree p,s;
   p=root;
   while(ss[i])
   {
       if(p->next[ss[i]-'a']==NULL)
       {
           s=NEW();
           p->next[ss[i]-'a']=s;
           p=s;
       }
       else p=p->next[ss[i]-'a'];
       i++;
   }
   p->count++;
}

void AC_Automation()
{
   int i,front,rear;
   Tree temp,p;
   front=rear=0;
   Q[front++]=root;
   while(rear<front)
   {
       temp=Q[rear];
       rear++;
       for(i=0;i<26;i++)
       {
           if(temp->next[i]==NULL)continue;
           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[front++]=temp->next[i];
       }
   }
}

int search()
{
   int i=0,sum=0;
   Tree p=root,temp;
   while(str[i])
   {
       while(p->next[str[i]-'a']==NULL && p!=root)
           p=p->fail;
       p=p->next[str[i]-'a'];
       if(p==NULL)
           p=root;
       temp=p;
       while(temp!=root && temp->count!=-1)
       {
           sum+=temp->count;
           temp->count=-1;
           temp=temp->fail;
       }
       i++;
   }
   return sum;
}

int main()
{
   int n,i,ans;
   char trie[55];
   scanf("%d",&ans);
   while(ans--)
   {
       root=NEW();
       scanf("%d",&n);
       for(i=0;i<n;i++)
       {
           scanf("%s",trie);
           Build(trie);
       }
       AC_Automation();
       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、付费专栏及课程。

余额充值