AC自动机

首先简要介绍一下AC自动机:Aho-Corasickautomation,该算法在1975年产生于贝尔实验室,是著名的多模匹配算法之一。一个常见的例子就是给出n个单词,再给出一段包含m个字符的文章,让你找出有多少个单词在文章里出现过。要搞懂AC自动机,先得有模式树(字典树)Trie和KMP模式匹配算法的基础知识。AC自动机算法分为3步:构造一棵Trie树,构造失败指针和模式匹配过程。

如果你对KMP算法和了解的话,应该知道KMP算法中的next函数(shift函数或者fail函数)是干什么用的。KMP中我们用两个指针i和j分别表示,A[i-j+1..i]与B[1..j]完全相等。也就是说,i是不断增加的,随着i的增加j相应地变化,且j满足以A[i]结尾的长度为j的字符串正好匹配B串的前 j个字符,当A[i+1]≠B[j+1],KMP的策略是调整j的位置(减小j值)使得A[i-j+1..i]与B[1..j]保持匹配且新的B[j+1]恰好与A[i+1]匹配,而next函数恰恰记录了这个j应该调整到的位置。同样AC自动机的失败指针具有同样的功能,也就是说当我们的模式串在Tire上进行匹配时,如果与当前节点的关键字不能继续匹配的时候,就应该去当前节点的失败指针所指向的节点继续进行匹配。

看下面这个例子:给定5个单词:say sheshr he her,然后给定一个字符串yasherhs。问一共有多少单词在这个字符串中出现过。我们先规定一下AC自动机所需要的一些数据结构,方便接下去的编程。

const int kind = 26;

struct node

{

node *fail; //失败指针

node *next[kind]; //Tire每个节点的个子节点(最多个字母)

int count; //是否为该单词的最后一个节点

node()

{ //构造函数初始化

fail=NULL;

count=0;

memset(next,NULL,sizeof(next));

}

}*q[500001]; //队列,方便用于bfs构造失败指针

 

char keyword[51]; //输入的单词

char str[1000001]; //模式串

int head,tail; //队列的头尾指针

有了这些数据结构之后,就可以开始编程了:

首先,将这5个单词构造成一棵Tire,如图-1所示。

void insert(char *str,node *root)

{

     node*p=root;

     inti=0,index;

     while(str[i])

{

     index=str[i]-'a';

     if(p->next[index]==NULL)p->next[index]=new node();

     p=p->next[index];

     i++;

 }

 p->count++; //在单词的最后一个节点count+1,代表一个单词

}

在构造完这棵Tire之后,接下去的工作就是构造下失败指针。构造失败指针的过程概括起来就一句话:设这个节点上的字母为C,沿着他父亲的失败指针走,直到走到一个节点,他的儿子中也有字母为C的节点。然后把当前节点的失败指针指向那个字母也为C的儿子。如果一直走到了root都没找到,那就把失败指针指向root。具体操作起来只需要:先把root加入队列(root的失败指针指向自己或者NULL),这以后我们每处理一个点,就把它的所有儿子加入队列,队列为空。

void build_ac_automation(node *root)

{

 int i;

 root->fail=NULL;

 q[head++]=root;

 while(head!=tail)

{

     node*temp=q[tail++];

     node*p=NULL;

     for(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];

         }

     }

 }

}

从代码观察下构造失败指针的流程:对照图-2来看,首先root的fail指针指向NULL,然后root入队,进入循环。第1次循环的时候,我们需要处理2个节点:root->next[‘h’-‘a’](节点h) 和root->next[‘s’-‘a’](节点s)。把这2个节点的失败指针指向root,并且先后进入队列,失败指针的指向对应图-2中的(1),(2)两条虚线;第2次进入循环后,从队列中先弹出h,接下来p指向h节点的fail指针指向的节点,也就是root;进入第13行的循环后,p=p->fail也就是p=NULL,这时退出循环,并把节点e的fail指针指向root,对应图-2中的(3),然后节点e进入队列;第3次循环时,弹出的第一个节点a的操作与上一步操作的节点e相同,把a的fail指针指向root,对应图-2中的(4),并入队;第4次进入循环时,弹出节点h(图中左边那个),这时操作略有不同。在程序运行到14行时,由于p->next[i]!=NULL(root有h这个儿子节点,图中右边那个),这样便把左边那个h节点的失败指针指向右边那个root的儿子节点h,对应图-2中的(5),然后h入队。以此类推:在循环结束后,所有的失败指针就是图-2中的这种形式。

最后,我们便可以在AC自动机上查找模式串中出现过哪些单词了。匹配过程分两种情况:(1)当前字符匹配,表示从当前节点沿着树边有一条路径可以到达目标字符,此时只需沿该路径走向下一个节点继续匹配即可,目标字符串指针移向下个字符继续匹配;(2)当前字符不匹配,则去当前节点失败指针所指向的字符继续匹配,匹配过程随着指针指向root结束。重复这2个过程中的任意一个,直到模式串走到结尾为止。

int query(node *root)

{

 inti=0,cnt=0,index,len=strlen(str);

 node *p=root;

 while(str[i])

{

index=str[i]-'a';

     while(p->next[index]==NULL&& p!=root) p=p->fail;

     p=p->next[index];

     p=(p==NULL)?root:p;

     node*temp=p;

     while(temp!=root&& temp->count!=-1)

{

         cnt+=temp->count;

         temp->count=-1;

         temp=temp->fail;

     }

     i++;

}

return cnt;

}

对照图-2,看一下模式匹配这个详细的流程,其中模式串为yasherhs。对于i=0,1。Trie中没有对应的路径,故不做任何操作;i=2,3,4时,指针p走到左下节点e。因为节点e的count信息为1,所以cnt+1,并且讲节点e的count值设置为-1,表示改单词已经出现过了,防止重复计数,最后temp指向e节点的失败指针所指向的节点继续查找,以此类推,最后temp指向root,退出while循环,这个过程中count增加了2。表示找到了2个单词she和he。当i=5时,程序进入第5行,p指向其失败指针的节点,也就是右边那个e节点,随后在第6行指向r节点,r节点的count值为1,从而count+1,循环直到temp指向root为止。最后i=6,7时,找不到任何匹配,匹配过程结束。

 

到此为止AC自动机算法的详细过程已经全部介绍结束,看两道例题:

1:(http://acm.hdu.edu.cn/showproblem.php?pid=2222

Problem Description

In the modern time, Search engine came into the life of everybody likeGoogle, Baidu, etc.

Wiskey also wants to bring this feature to his image retrieval system.

Every image have a long description, when users type some keywords to findthe image, the system will match the keywords with description of image andshow the image which the most keywords be matched.

To simplify the problem, giving you a description of image, and somekeywords, you should tell me how many keywords will be match.

 

Input

First line will contain one integer means how many cases will follow by.

Each case will contain two integers N means the number of keywords and Nkeywords follow. (N <= 10000)

Each keyword will only contains characters 'a'-'z', and the length will benot longer than 50.

The last line is the description, and the length will be not longer than1000000.

 

Output

Print how many keywords are contained in the description.

 

Sample Input

1 5 she he say shr her yasherhs

 

Sample Output

3

代码见上。

2:(http://acm.hdu.edu.cn/showproblem.php?pid=1277

Problem Description

我们大家经常用google检索信息,但是检索信息的程序是很困难编写的;现在请你编写一个简单的全文检索程序。

问题的描述是这样的:给定一个信息流文件,信息完全有数字组成,数字个数不超过60000个,但也不少于60个;再给定一个关键字集合,其中关键字个数不超过10000个,每个关键字的信息数字不超过60个,但也不少于5个;两个不同的关键字的前4个数字是不相同的;由于流文件太长,已经把它分成多行;请你编写一个程序检索出有那些关键字在文件中出现过。

 

Input

第一行是两个整数MNM表示数字信息的行数,N表示关键字的个数;接着是M行信息数字,然后是一个空行;再接着是N行关键字;每个关键字的形式是:[Key No. 1] 84336606737854833158

 

Output

输出只有一行,如果检索到有关键字出现,则依次输出,但不能重复,中间有空格,形式如:Found key: [Key No. 9] [Key No. 5];如果没找到,则输出形如:No key can be found !

 

Sample Input

20 10

646371829920732613433350295911348731863560763634906583816269637943246892596447991938395877747771811648872332524287543417420073458038799863383943942530626367011418831418830378814827679789991249141417051280978492595526784382732523080941390128 848936060512743730770176538411912533308591624872304820548423057714962038959390276719431970894771269272915078424294911604285668850536322870175463184619212279227080486085232196545993274120348544992476883699966392847818898765000210113407285843826588950728649155284642040381621412034311030525211673826615398392584951483398200573382259746978916038978673319211750951759887080899375947416778162964542298155439321112519055818097642777682095251801728347934613082147096788006630252328830397651057159088107635467760822355648170303701893489665828841446069075452303785944262412169703756833446978261465128188378490310770144518810438159567647733036073099159346768788307780542503526691711872185060586699672220882332373316019934540754940773329948050821544112511169610221737386427076709247489217919035158663949436676762790541915664544880091332011868983231199331629190771638894322709719381139120258155869538381417179544000361739177065479939154438487026200359760114591903421347697

[Key No. 1] 934134543994403697353070375063

[Key No. 2] 261985859328131064098820791211

[Key No. 3] 306654944587896551585198958148

[Key No. 4] 338705582224622197932744664740

[Key No. 5] 619212279227080486085232196545

[Key No. 6] 333721611669515948347341113196

[Key No. 7] 558413268297940936497001402385

[Key No. 8] 212078302886403292548019629313

[Key No. 9] 877747771811648872332524287543

[Key No. 10] 488616113330539801137218227609

 

Sample Output

Found key: [Key No. 9] [Key No. 5]

AC CODE

 

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

const int kind = 10;

struct node

{

node *fail;

node *next[kind];

int count;

int flag;

node()

{

fail=NULL;

count=0;

flag=0;

memset(next,NULL,sizeof(next));

}

}*q[1000000];

 

char keyword[70];

char str[1000000];

int head,tail;

char flag[100005];

 

void insert(char *str,node *root,int id)

{

node *p=root;

int i=0,index;

while(str[i])

{

index=str[i]-'0';

if( p->next[index]==NULL )p->next[index]=new node();

p=p->next[index];

i++;

}

p->count=id;

}

 

void build_ac_automation(node *root)

{

int i;

root->fail=NULL;

q[head++]=root;

while( head!=tail )

{

node *temp=q[tail++];

node *p=NULL;

for( i=0;i<10; 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 i=0,cnt=0,index,len=strlen(str);

node *p=root;

while( str[i] )

{

index=str[i]-'0';

while( p->next[index]==NULL &&p!=root ) p=p->fail;

p=p->next[index];

p=(p==NULL)?root:p;

node *temp=p;

while( temp!=root && temp->count)

{

// cnt+=temp->count;

// temp->count=-1;

flag[temp->count]=1;

temp=temp->fail;

}

i++;

}

return cnt;

}

 

int main()

{

int n,m,t,i,ms;

char *p;

memset(flag,0,sizeof(flag));

while(scanf("%d%d",&n,&m)!=EOF )

{

p=str;

for( i=0; i<n; i++ )

{

scanf("%s",p);

t=strlen(p);

p+=t;

}

scanf("%*c%*c");

head=tail=0;

node *root=new node();

// getchar();

ms=m;

while( ms-- )

{

scanf("[Key No. %d] ",&t);

gets(keyword);

insert(keyword,root,t);

}

build_ac_automation(root);

query(root);

t=0;

for( i=m; i>=0; i-- )

{

if( flag[i] )

{

if( !t ) printf("Found key:");

printf(" [Key No. %d]",i);

t++;

}

}

if( !t ) printf("No key can be found!");

printf("\n");

}

return 0;

}

转自:http://blog.sina.com.cn/s/blog_80eb17940100rtru.html


呵呵
原文地址:https://www.cnblogs.com/gqtcgq/p/7247277.html