HDU 2222  Keywords Search(AC自…

来源:互联网 发布:汇川plc编程软件安装 编辑:程序博客网 时间:2024/06/05 10:38

题目链接: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

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

charstr[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;
}

voidBuild(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++;
}

voidAC_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];
      }
   }
}

intsearch()
{
   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;
}

intmain()
{
   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;
}

原创粉丝点击