AC自动机——Aho-Corasick Automaton

来源:互联网 发布:日本直播软件排名 编辑:程序博客网 时间:2024/04/30 23:46

这是一个英文版的讲的比较好的AC自动机资料。

http://www.cs.uku.fi/~kilpelai/BSA05/lectures/slides04.pdf

如果不爱看英文,可以看我整理的大致的翻译,再加上点解释说明啥的,建议中英两个版本结合着看,毕竟我翻译的里面可能有些错误。

http://download.csdn.net/download/morgan_xww/4476863


可以预览一下文档中的截图:

我的模板:

class ACAutomaton{public:    static const int MAX_N = 10000 * 50 + 5;        //最大结点数:模式串个数 X 模式串最大长度    static const int CLD_NUM = 26;        //从每个结点出发的最多边数,字符集Σ的大小,一般是26个字母    int n;                          //trie树当前结点总数    int id['z'+1];                  //字母x对应的结点编号为id[x]    int fail[MAX_N];                //fail指针    int tag[MAX_N];                 //根据题目而不同    int trie[MAX_N][CLD_NUM];       //trie树,也就是goto函数    void init()    {        for (int i = 0; i < CLD_NUM; i++)            id['a'+i] = i;    }    void reset()    {        memset(trie[0], -1, sizeof(trie[0]));        tag[0] = 0;        n = 1;    }    //插入模式串s,构造单词树(keyword tree)    void add(char *s)    {        int p = 0;        while (*s)        {            int i = id[*s];            if ( -1 == trie[p][i] )            {                memset(trie[n], -1, sizeof(trie[n]));                tag[n] = 0;                trie[p][i] = n++;            }            p = trie[p][i];            s++;        }        tag[p]++;         //因题而异    }    //构造AC自动机,用BFS来计算每个结点的fail指针,就是构造trie图    void construct()    {        queue<int> Q;        fail[0] = 0;        for (int i = 0; i < CLD_NUM; i++)        {            if (-1 != trie[0][i])            {                fail[trie[0][i]] = 0; //root下的第一层结点的fail指针都指向root                Q.push(trie[0][i]);            }            else            {                trie[0][i] = 0;    //这是阶段一中的第2步            }        }        while ( !Q.empty() )        {            int u = Q.front();            Q.pop();            for (int i = 0; i < CLD_NUM; i++)            {                int &v = trie[u][i];                if ( -1 != v )                {                    Q.push(v);                    fail[v] = trie[fail[u]][i];                    tag[u] += tag[fail[u]];     //因题而异,某些题目中不需要这句话                }                else                {            //当trie[u][i]==-1时,设置其为trie[fail[u]][i],就构造了trie图                    v = trie[fail[u]][i];                }            }        }    }    //因题而异    //在目标串t中匹配模式串    int solve(char *t)    {        int q = 0, ret = 0;        while ( *t )        {            q = trie[q][id[*t]];            int u = q;            while ( u != 0 )            {                ret += tag[u];                tag[u] = 0;                u = fail[u];            }            t++;        }        return ret;    }} ac;