AC自动机算法详解

http://www.cppblog.com/mythit/archive/2009/04/21/80633.html


首先简要介绍一下AC自动机:Aho-Corasick automation,该算法在1975年产生于贝尔实验室,是著名的多模匹配算法之一。一个常见的例子就是给出n个单词,再给出一段包含m个字符的文章,让你找出有多少个单词在文章里出现过。要搞懂AC自动机,先得有模式树(字典树)TrieKMP模式匹配算法的基础知识。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 she shr he her,然后给定一个字符串yasherhs。问一共有多少单词在这个字符串中出现过。我们先规定一下AC自动机所需要的一些数据结构,方便接下去的编程。


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


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

 对照图-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自动机算法的详细过程已经全部介绍结束,看一道例题:http://acm.hdu.edu.cn/showproblem.php?pid=2222

Problem Description
In the modern time, Search engine came into the life of everybody like Google, 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 find the image, the system will match the keywords with description of image and show the image which the most keywords be matched.
To simplify the problem, giving you a description of image, and some keywords, 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 N keywords follow. (N <= 10000)
Each keyword will only contains characters 'a'-'z', and the length will be not longer than 50.
The last line is the description, and the length will be not longer than 1000000.
 

Output
Print how many keywords are contained in the description.
 

Sample Input
1
5
she
he
say
shr
her
yasherhs
 

Sample Output
3

#include <iostream>
#include <queue>

using namespace std;

char desc[1000000];
char keyword[51];

class Node {
public:
    bool m_isLeaf;
    Node *nodes[26];
   
    Node *falure;
    char m_val;
    int count;

public:
    Node(char val='\0', bool leaf = false) {
        m_val = val;
        m_isLeaf = leaf;
       
        falure = NULL;
        count = 0;
        memset(nodes, 0, sizeof(nodes));
    }
    
    ~Node() {
        for (int i = 0; i < 26; ++i)
            if (nodes[i])
                delete nodes[i];
    }

};

class ACTree {
    Node root;
public:
    void insert(char* str) {
        Node *head = &root;
        while(*str) {
            int i = *str - 'a';
            if(head->nodes[i] != NULL) head = head->nodes[i];
            else {
                head->nodes[i] = new Node(*str);
                head = head->nodes[i];
            }
            ++str;
        }
        head->m_isLeaf = true;
        head->count += 1;
    }
    void constructACTree() {
        queue<Node *> qu;
        qu.push(&root);
        
        while(!qu.empty()) {
            Node * tmp = qu.front();
            qu.pop();
            for(int i = 0; i < 26; ++i) {
                //tmp就是待处理节点的父节点
                if (tmp->nodes[i]) {
                    if (tmp == &root) {
                        tmp->nodes[i]->falure = &root;
                    }
                    else {
                        Node * p = tmp->falure;
                        while (p) {
                            if (p->nodes[i]) {
                                tmp->nodes[i]->falure = p->nodes[i];
                                break;
                            }
                            p = p->falure;
                        }
                        if (p == NULL)
                            tmp->nodes[i]->falure = &root;
                    }//if else

                    qu.push(tmp->nodes[i]);
                }//if
                    
            }//for
            
        }//while

    }

    //假设不存在一个模式串是另一个模式串的子串
    //不能统计匹配的关键词的个数
    int match(char *str) {
        int count = 0;
        while (*str) {
            char *p = str;
            Node *n = &root;
            while (n && p) {
                int i = *p - 'a';
                if (n->nodes[i]) {
                    n = n->nodes[i];
                    ++p;
                    
                    if (n->m_isLeaf) {
                        ++count;

                        str = p;
                        break;
                    }
                }
                else {
                    n = n->falure;
                }

            }

            if (n == NULL) {
                ++str;
            }
        }

        return count;
    }

    //如果字符串s1..n匹配到trie树中的某个节点ni,设此时匹配的字符是sh...i, 那么ni的失败指针所指向的节点nj,必然可以匹配sk...i,其中,k>h
    //即失败指针所指向的节点,这个节点到root的路径,必然是已经匹配字符串的子串
    int countKeys(char *str) {
        int count = 0;
        Node *p = &root;//这个可以看做是主线查询
        while(*str) {
            int i = *str - 'a';
            //如果p->nodes[i]不等于null,则跳出循环,继续在这个分支上查找;否则,就跳到另一个分支
            while(p->nodes[i] == NULL && p != &root) p = p->falure;
            
            p = p->nodes[i];//

            //所有分支均不能匹配这个字串,所以要从头开始匹配
            if(p == NULL)
                p = &root;
           

            Node *tmp = p;
            while(tmp != &root && tmp->count != -1) {
                
                    count += tmp->count;
                    tmp->count = -1;//删除这个叶子
                
                tmp = tmp->falure;
            }
            ++str;

        }

        return count;

    }

    ~ACTree() {
       /* for (int i = 0; i < 26; ++i)
            if (root.nodes[i])
                delete root.nodes[i];*/
    }
};

int main() {
    int t;
    scanf("%d", &t);
    while (t--) {
        ACTree tree;
        int n;
        scanf("%d", &n);
        while(n--) {
            scanf("%s", keyword);
            tree.insert(keyword);
        }
        tree.constructACTree();
        scanf("%s", desc);
        printf("%d\n", tree.countKeys(desc));
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值