码迷,mamicode.com
首页 > 其他好文 > 详细

【小结】AC自动机

时间:2015-08-16 09:26:10      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:

DFAAC自动机:

  • 考虑以下单词: {she, he, her},字母表26个小写字母
  • 我们先画出它Trie树的模样
    技术分享

  • 注意,双圈的是包含单词结尾的位置。然后我们尝试将它稍加改造,变成一个DFA

  • 对每一个状态,必须补充下一个字母为其它(比如从起始状态出发,输入一个h,匹配上了,接下来输入可能为az,我们已经有了e的箭头,还要补上其它的)。这里是补上根节点和从根走sh的那个后的结果:
    技术分享
  • 注意正则表达式[sh]表示除s,h外所有字母。我们考虑下面那个sh对应的状态,遇到s转到它的父节点,遇到h转到右边那个节点,遇到e到下面一个状态,遇到其它则直接转回起始状态。补充完余下的转移,完成后就可以拿来用了。比如我们拿到一个字符串,就可以想象自己就是这台DFA,每次读入一个字符,按照箭头的指示转至不同的状态,只要遇到了一个接受状态(图中双圈),就认为匹配上一次。我们发现,这台自动机已经可以完成我们要求的多模式匹配的任务了!也即通过对一堆串构造DFA,以后拿到一个串M,只需要每次读一个字符,然后走箭头,就可以完成M和这一大堆串的匹配~那么单次匹配的复杂度就只有O(|M|)了,这是线性的!
  • 下面,稍加转化,就可以将上述DFA变成AC自动机。依然考虑左边这个sh对应的状态,如果遇到e,转到下面一个转态,不需要改变;但是如果遇到了sh,我们并不是直接按照sh的指示完成转换然后继续后面的匹配,而是保留这个s或者h,先转到起始状态,然后再重新读入s或者h继续匹配。也就是说,只要发生了“失配”,就转到另一个状态,继续处理。这么做的好处是容易在代码上实现。于是sh对应状态在遇到s或者h时,也会转向起始状态,这个转向就时AC自动机的所谓fail指针。在匹配时,用一个tmp指针模拟我们的手指,开始时指向起始状态,遇到s,就按照s箭头的指示移动到对应状态,直到所有字符都读完,匹配结束。
  • 留个板子
/* **********************************************

  File Name: ac_automata.cpp

  Auther: zhengdongjian@tju.edu.cn

  Created Time: 2015年08月14日 星期五 08时41分23秒

*********************************************** */
#include <bits/stdc++.h>
using namespace std;

typedef pair<int, int> P;
const double EPS = 1e-8;
const double PI = acos(-1.0);

const int MAX = 500007;
const int MAXD = 26; //26 alphas
struct Trie {
    /* 
     * nxt & end is used in trie
     * fail is for ac automata
     */
    int nxt[MAX][MAXD], fail[MAX], end[MAX];
    int root, L; //root node, length(the nodes has been malloc)[0, L]
    int newnode() {
        memset(nxt[L], -1, sizeof(int) * MAXD);
        end[L++] = 0;
        return L - 1;
    }
    void clear() {
        L = 0;
        root = newnode();
    }
    void insert(char* buf) {
        int len = strlen(buf);
        int now = root;
        for (int i = 0; i < len; ++i) {
            if (nxt[now][buf[i] - ‘a‘] == -1) {
                nxt[now][buf[i] - ‘a‘] = newnode();
            }
            now = nxt[now][buf[i] - ‘a‘];
        }
        ++end[now];
    }
    void build() {
        queue<int> Q;
        fail[root] = root;
        for (int i = 0; i < MAXD; ++i) {
            if (nxt[root][i] == -1) {
                nxt[root][i] = root;
            } else {
                fail[nxt[root][i]] = root;
                Q.push(nxt[root][i]);
            }
        }

        while (!Q.empty()) {
            int now = Q.front();
            Q.pop();

            for (int i = 0; i < MAXD; ++i) {
                if (nxt[now][i] == -1) {
                    nxt[now][i] = nxt[fail[now]][i];
                } else {
                    fail[nxt[now][i]] = nxt[fail[now]][i];
                    Q.push(nxt[now][i]);
                }
            }
        }
    }
    int query(char* buf, int len = -1) {
        if (len == -1) {
            len = strlen(buf);
        }
        int now = root;
        int res = 0;
        for (int i = 0; i < len; ++i) {
            now = nxt[now][buf[i] - ‘a‘];
            int tmp = now;
            while (tmp != root) {
                res += end[tmp];
                end[tmp] = 0; //不重复,若可重复此处不置0即可
                tmp = fail[tmp];
            }
        }
        return res;
    }
    void debug() {
        for (int i = 0; i < L; ++i) {
            printf("%d, %d, %d, [%d", i, fail[i], end[i], nxt[i][0]);
            for (int j = 1; j < MAXD; ++j) {
                printf(" %d", nxt[i][j]);
            }
            puts("]");
        }
    }
} ac;

const int MAXL = 64;
char str[MAXL];
char buf[MAX << 1];

int main() {
    int T;
    scanf(" %d", &T);
    while (T--) {
        int n;
        scanf(" %d", &n);
        ac.clear();
        for (int i = 0; i < n; ++i) {
            scanf(" %s", str);
            ac.insert(str);
        }
        ac.build();

        scanf(" %s", buf);
        printf("%d\n", ac.query(buf));
    }
    return 0;
}

几个简单的小题目

  • hdu2222,First attempt
/* **********************************************

  File Name: ac_automata.cpp => hdu2222

  Auther: zhengdongjian@tju.edu.cn

  Created Time: 2015年08月14日 星期五 08时41分23秒

*********************************************** */
#include <bits/stdc++.h>
using namespace std;

typedef pair<int, int> P;
const double EPS = 1e-8;
const double PI = acos(-1.0);

const int MAX = 500007;
const int MAXD = 26; //26 alphas
struct Trie {
    /* 
     * nxt & end is used in trie
     * fail is for ac automata
     */
    int nxt[MAX][MAXD], fail[MAX], end[MAX];
    int root, L; //root node, length(the nodes has been malloc)[0, L]
    int newnode() {
        memset(nxt[L], -1, sizeof(int) * MAXD);
        end[L++] = 0;
        return L - 1;
    }
    void clear() {
        L = 0;
        root = newnode();
    }
    void insert(char* buf) {
        int len = strlen(buf);
        int now = root;
        for (int i = 0; i < len; ++i) {
            if (nxt[now][buf[i] - ‘a‘] == -1) {
                nxt[now][buf[i] - ‘a‘] = newnode();
            }
            now = nxt[now][buf[i] - ‘a‘];
        }
        ++end[now];
    }
    void build() {
        queue<int> Q;
        fail[root] = root;
        for (int i = 0; i < MAXD; ++i) {
            if (nxt[root][i] == -1) {
                nxt[root][i] = root;
            } else {
                fail[nxt[root][i]] = root;
                Q.push(nxt[root][i]);
            }
        }

        while (!Q.empty()) {
            int now = Q.front();
            Q.pop();

            for (int i = 0; i < MAXD; ++i) {
                if (nxt[now][i] == -1) {
                    nxt[now][i] = nxt[fail[now]][i];
                } else {
                    fail[nxt[now][i]] = nxt[fail[now]][i];
                    Q.push(nxt[now][i]);
                }
            }
        }
    }
    int query(char* buf, int len = -1) {
        if (len == -1) {
            len = strlen(buf);
        }
        int now = root;
        int res = 0;
        for (int i = 0; i < len; ++i) {
            now = nxt[now][buf[i] - ‘a‘];
            int tmp = now;
            while (tmp != root) {
                res += end[tmp];
                end[tmp] = 0; //不重复,若可重复此处不置0即可
                tmp = fail[tmp];
            }
        }
        return res;
    }
    void debug() {
        for (int i = 0; i < L; ++i) {
            printf("%d, %d, %d, [%d", i, fail[i], end[i], nxt[i][0]);
            for (int j = 1; j < MAXD; ++j) {
                printf(" %d", nxt[i][j]);
            }
            puts("]");
        }
    }
} ac;

const int MAXL = 64;
char str[MAXL];
char buf[MAX << 1];

int main() {
    int T;
    scanf(" %d", &T);
    while (T--) {
        int n;
        scanf(" %d", &n);
        ac.clear();
        for (int i = 0; i < n; ++i) {
            scanf(" %s", str);
            ac.insert(str);
        }
        ac.build();

        scanf(" %s", buf);
        printf("%d\n", ac.query(buf));
    }
    return 0;
}
  • hdu2896
  • 病毒保证不同,简单统计,随便搞
/* **********************************************

  File Name: 2896.cpp

  Auther: zhengdongjian@tju.edu.cn

  Created Time: 2015年08月14日 星期五 11时25分51秒

*********************************************** */
#include <bits/stdc++.h>
using namespace std;

typedef pair<int, int> P;
const double EPS = 1e-8;
const double PI = acos(-1.0);
const int MAX = 100007;
const int MAXD = 128;
struct Trie {
    int nxt[MAX][MAXD], fail[MAX], end[MAX];
    int root, L;

    int newnode() {
        memset(nxt[L], -1, sizeof(int) * MAXD);
        end[L++] = -1;
        return L - 1;
    }

    void clear() {
        L = 0;
        root = newnode();
    }

    void insert(char* buf, int _end) {
        int len = strlen(buf);
        int now = root;
        for (int i = 0; i < len; ++i) {
            if (nxt[now][(int)buf[i]] == -1) {
                nxt[now][(int)buf[i]] = newnode();
            }
            now = nxt[now][(int)buf[i]];
        }
        end[now] = _end;
    }

    void build() {
        queue<int> Q;
        fail[root] = root;
        for (int i = 0; i < MAXD; ++i) {
            if (nxt[root][i] == -1) {
                nxt[root][i] = root;
            } else {
                fail[nxt[root][i]] = root;
                Q.push(nxt[root][i]);
            }
        }

        while (!Q.empty()) {
            int now = Q.front();
            Q.pop();

            for (int i = 0; i < MAXD; ++i) {
                if (nxt[now][i] == -1) {
                    nxt[now][i] = nxt[fail[now]][i];
                } else {
                    fail[nxt[now][i]] = nxt[fail[now]][i];
                    Q.push(nxt[now][i]);
                }
            }
        }
    }
    set<int> query(char* buf) {
        int len = strlen(buf);
        int now = root;
        set<int> res;
        for (int i = 0; i < len; ++i) {
            now = nxt[now][(int)buf[i]];
            int tmp = now;
            while (tmp != root) {
                if (~end[tmp]) {
                    res.insert(end[tmp]);
                }
                tmp = fail[tmp];
            }
        }
        return res;
    }
} ac;
char buf[MAX];

int main() {
    int n, m;
    while (~scanf(" %d", &n)) {
        ac.clear();
        for (int i = 1; i <= n; ++i) {
            scanf(" %s", buf);
            ac.insert(buf, i);
        }
        ac.build();
        scanf(" %d", &m);
        int sum = 0;
        for (int i = 1; i <= m; ++i) {
            scanf(" %s", buf);
            auto v = ac.query(buf);
            if (!v.empty()) {
                ++sum;
                printf("web %d:", i);
                for (auto it = v.begin(); it != v.end(); ++it) {
                    printf(" %d", *it);
                }
                puts("");
            }
        }
        printf("total: %d\n", sum);
    }
    return 0;
}
  • hdu3065
  • 要打印匹配串:打标记,Trie上节点打前驱和字符标记。P.S.空间上还可以优化
/* **********************************************

  File Name: 3065.cpp

  Auther: zhengdongjian@tju.edu.cn

  Created Time: 2015年08月14日 星期五 11时46分10秒

*********************************************** */
#include <bits/stdc++.h>
using namespace std;

typedef pair<int, int> P;
const double EPS = 1e-8;
const double PI = acos(-1.0);

const int MAX = 50007;
const int MAXD = 128; //26 alphas
struct Trie {
    /* 
     * nxt & end is used in trie
     * fail is for ac automata
     */
    int nxt[MAX][MAXD], fail[MAX], end[MAX], pre[MAX];
    char dad[MAX];
    int root, L; //root node, length(the nodes has been malloc)[0, L]
    int newnode() {
        memset(nxt[L], -1, sizeof(int) * MAXD);
        pre[L] = -1;
        end[L++] = 0;
        return L - 1;
    }
    void clear() {
        L = 0;
        root = newnode();
    }
    void insert(char* buf) {
        int len = strlen(buf);
        int now = root;
        for (int i = 0; i < len; ++i) {
            if (nxt[now][(int)buf[i]] == -1) {
                nxt[now][(int)buf[i]] = newnode();
                pre[nxt[now][(int)buf[i]]] = now;
                dad[nxt[now][(int)buf[i]]] = buf[i];
            }
            now = nxt[now][(int)buf[i]];
        }
        ++end[now];
    }

    void build() {
        queue<int> Q;
        fail[root] = root;
        for (int i = 0; i < MAXD; ++i) {
            if (nxt[root][i] == -1) {
                nxt[root][i] = root;
            } else {
                fail[nxt[root][i]] = root;
                Q.push(nxt[root][i]);
            }
        }

        while (!Q.empty()) {
            int now = Q.front();
            Q.pop();

            for (int i = 0; i < MAXD; ++i) {
                if (nxt[now][i] == -1) {
                    nxt[now][i] = nxt[fail[now]][i];
                } else {
                    fail[nxt[now][i]] = nxt[fail[now]][i];
                    Q.push(nxt[now][i]);
                }
            }
        }
    }
    map<int, int> query(char* buf, int len = -1) {
        if (len == -1) {
            len = strlen(buf);
        }
        int now = root;
        map<int, int> res;
        for (int i = 0; i < len; ++i) {
            now = nxt[now][(int)buf[i]];
            int tmp = now;
            while (tmp != root) {
                if (end[tmp] > 0) {
                    ++res[tmp];
                }
                tmp = fail[tmp];
            }
        }
        return res;
    }
    void debug() {
        for (int i = 0; i < L; ++i) {
            printf("%d, %d, %d, [%d", i, fail[i], end[i], nxt[i][0]);
            for (int j = 1; j < MAXD; ++j) {
                printf(" %d", nxt[i][j]);
            }
            puts("]");
        }
    }
} ac;

const int MAXL = 64;
char str[MAXL];
char buffer[MAX * 40];

int main() {
    int n;
    while (~scanf(" %d", &n)) {
        ac.clear();
        for (int i = 1; i <= n; ++i) {
            scanf(" %s", str);
            ac.insert(str);
        }
        ac.build();
        scanf(" %s", buffer);
        auto mp = ac.query(buffer);
        for (auto it = mp.begin(); it != mp.end(); ++it) {
            int now = it->first;
            int idx = MAXL - 1;
            str[idx--] = ‘\0‘;
            while (now != ac.root) {
                str[idx--] = ac.dad[now];
                now = ac.pre[now];
            }
            ++idx;
            printf("%s: %d\n", str + idx, it->second);
        }
    }
    return 0;
}
  • zoj3430
  • 解码一下即可。debug了好久,最后发现Base64直接解码出来的字符可能不是ASCII码,就如1111 1111对应到ASCII后是EOF真让人难堪。。。所以字符集开到256就可以过了…一部分调试中间修改导致整个代码看起来丑陋了一些,不愿改了。。
/* **********************************************

  File Name: 3430.cpp

  Auther: zhengdongjian@tju.edu.cn

  Created Time: 2015年08月14日 星期五 13时28分38秒

*********************************************** */
#include <bits/stdc++.h>
using namespace std;

typedef pair<int, int> P;
const double EPS = 1e-8;
const double PI = acos(-1.0);
const int MAX = 50007;
const int MAXD = 256;

/*
 * Base64 Decode
 */
static const char cb64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
bool pool[50007];
inline int dic64(char& c) {
    if (isupper(c)) {
        return c - ‘A‘;
    } else if (islower(c)) {
        return c - ‘a‘ + 26;
    } else if (isdigit(c)) {
        return c - ‘0‘ + 52;
    } else {
        return c == ‘+‘ ? 62 : 63;
    }
}
void decode64(char source[], int dest[]) {
    int len = strlen(source);
    int bit = len * 6;
    memset(pool, false, sizeof(bool) * bit);
    while (source[len - 1] == ‘=‘) {
        --len;
        bit -= 8;
    }
    //printf("bit = %d\n", bit);
    for (int i = 0, j = 0; i < len; ++i, j += 6) {
        int c = dic64(source[i]);
        for (int k = j + 5; k >= j; --k) {
            pool[k] = c & 1;
            c >>= 1;
        }
    }
    int p = 0;
    for (int i = 0; i < bit; i += 8) {
        dest[p] = 0;
        for (int j = 0; j < 8; ++j) {
            dest[p] <<= 1;
            if (pool[i + j]) {
                ++dest[p];
                //dest[p] = (char)((int)dest[p] + 1);
            }
        }
        ++p;
    }
    dest[p] = -1;
}
/**********************************************/

struct Trie {
    /* 
     * nxt & end is used in trie
     * fail is for ac automata
     */
    int nxt[MAX][MAXD], fail[MAX], end[MAX];
    int root, L; //root node, length(the nodes has been malloc)[0, L]
    int newnode() {
        memset(nxt[L], -1, sizeof(int) * MAXD);
        end[L++] = 0;
        return L - 1;
    }
    void clear() {
        L = 0;
        root = newnode();
    }
    void insert(int* buf, int _id) {
        int* p = buf;
        int now = root;
        while (~(*p)) {
            if (nxt[now][*p] == -1) {
                nxt[now][*p] = newnode();
            }
            now = nxt[now][*p++];
        }
        end[now] = _id;
    }
    void build() {
        queue<int> Q;
        fail[root] = root;
        for (int i = 0; i < MAXD; ++i) {
            if (nxt[root][i] == -1) {
                nxt[root][i] = root;
            } else {
                fail[nxt[root][i]] = root;
                Q.push(nxt[root][i]);
            }
        }

        while (!Q.empty()) {
            int now = Q.front();
            Q.pop();

            for (int i = 0; i < MAXD; ++i) {
                if (nxt[now][i] == -1) {
                    nxt[now][i] = nxt[fail[now]][i];
                } else {
                    fail[nxt[now][i]] = nxt[fail[now]][i];
                    Q.push(nxt[now][i]);
                }
            }
        }
    }
    set<int> query(int* buf) {
        int* p = buf;
        int now = root;
        set<int> res;
        while (~(*p)) {
            now = nxt[now][*p++];
            int tmp = now;
            while (tmp != root) {
                if (end[tmp]) {
                    res.insert(end[tmp]);
                }
                tmp = fail[tmp];
            }
        }
        return res;
    }
    void debug() {
        for (int i = 0; i < L; ++i) {
            printf("%d, %d, %d, [%d", i, fail[i], end[i], nxt[i][0]);
            for (int j = 1; j < MAXD; ++j) {
                printf(" %d", nxt[i][j]);
            }
            puts("]");
        }
    }
} ac;

const int MAXL = 128;
char str[MAXL];
char buf[MAX];
int jj[MAX];

int main() {
    /*
    while (cin >> buf) {
        decode64(buf, buf);
        cout << buf << endl;
    }
    return 0;
    */

    int n;
    while (~scanf(" %d", &n)) {
        ac.clear();
        for (int i = 1; i <= n; ++i) {
            scanf(" %s", str);
            decode64(str, jj);
            ac.insert(jj, i);
        }
        ac.build();

        int m;
        scanf(" %d", &m);
        while (m--) {
            scanf(" %s", buf);
            decode64(buf, jj);
            printf("%d\n", (int)ac.query(jj).size());
        }
        puts("");
    }
    return 0;
}

版权声明:那泥烤去看鸭o o

【小结】AC自动机

标签:

原文地址:http://blog.csdn.net/bit_line/article/details/47699647

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!