HDU 2222 Keywords Search(我的第一道AC自动机,模板题)

来源:互联网 发布:身份证模拟软件 编辑:程序博客网 时间:2024/06/05 09:35

链接:

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


分析与总结:

作为著名的AC自动机入门题,已经给说烂了,我也没什么好说的了。 用来测试自己学了AC自动机之后写的代码的。

话说这模板也有两种形式的,一种是用静态数组的,刘汝佳的大白书上就是那种,还有一种是我采用的这种指针形式的(但也是先静态开辟数组节点,然后分配数组空间上的给指针,速度和开辟的内存大小也没差),纠结了很久之后,发现我还是喜欢指针形式的,就坚持用这种了吧。



代码:

#include<iostream>#include<cstdio>#include<cstring>#include<queue>using namespace std;const int MAX_NODE = 1000005;const int SIGMA_SIZE = 26;int size;char str[MAX_NODE];char keyword[55];struct node{    node* fail;    node* next[SIGMA_SIZE];    int count;    void init(){        fail=NULL; count=0;         memset(next, 0, sizeof(next));    }};class AC_Automation{public:    void init();    void insert(char* str);    void getFail();    int find(char* str);private:    node* new_node();    node Heap[MAX_NODE];    node* root;    int size;};node* AC_Automation::new_node(){    Heap[size].init();    return &Heap[size++];}void AC_Automation::init(){    size=0;    root=new_node();}void AC_Automation::insert(char* str){    node* p=root;    for( ; *str; ++str){        int ch=*str-'a';        if(p->next[ch]==NULL)            p->next[ch] = new_node();        p=p->next[ch];    }    ++p->count;}void AC_Automation::getFail(){    queue<node*>Q;    Q.push(root);    while(!Q.empty()){        node* tmp=Q.front(); Q.pop();        node* p;        for(int i=0; i<SIGMA_SIZE; ++i){            node*& now=tmp->next[i];            if(now != NULL){                Q.push(now);                if(tmp==root){                    now->fail=root;                    continue;                }                p = tmp->fail;                while(p != NULL){                    if(p->next[i] != NULL){                        now->fail = p->next[i];                        break;                    }                    p=p->fail;                }                if(p==NULL) now->fail=root;            }            else{  // 构建成Trie图,可提高效率                if(tmp==root) now=root;                else now=tmp->fail->next[i];            }        }    }}int AC_Automation::find(char* str){    node* p=root;    int cnt=0;    for( ; *str; ++str){        char ch=*str-'a';        p = p->next[ch];        if(p==NULL) p=root;        node* tmp=p;        while(tmp!=root && tmp->count!=-1){            cnt += tmp->count;            tmp->count=-1;            tmp=tmp->fail;        }    }    return cnt;}AC_Automation ac;int main(){    int nCase, m;    scanf("%d",&nCase);    while(nCase--){        scanf("%d%*c",&m);        // init AC Automation        ac.init();        while(m--){            gets(keyword);            ac.insert(keyword);        }        gets(str);        ac.getFail();        printf("%d\n", ac.find(str));    }    return 0;}



 ——  生命的意义,在于赋予它意义士。

          原创 http://blog.csdn.net/shuangde800 , By   D_Double  (转载请标明)



原创粉丝点击