AC自动机

来源:互联网 发布:java开发的经典书籍 编辑:程序博客网 时间:2024/05/16 02:19

终于可以学习AC自动机,一直觉得这个东西很神秘,参照了大神的讲解和bin神的代码,算是理解了ac自动机的原理了,其实就是多模式串的匹配,一些处理的方法都十分的巧妙,写这个算其实可以参照kmp的next回溯,这样理解会更透彻。大神讲解 bin神


struct AC{    int next[500005][26],fail[500005],end[500005],Q[500005];    int root,cnt;    void Init()    {        cnt=0;        root=newNode();    }    int newNode()    {        for(int i=0;i<26;i++)            next[cnt][i]=-1;        end[cnt++]=0;        return cnt-1;    }    void Insert(char buff[])    {        int now=root;        int len=strlen(buff);        for(int i=0,k;i<len;i++)        {            k=buff[i]-'a';            if(next[now][k]==-1)                next[now][k]=newNode();            now=next[now][k];        }        end[now]++;///计算这种单词的数量    }    void build()    {        int front,rear;        front=rear=0;        int now=root;        for(int i=0;i<26;i++)        {            if(next[now][i]==-1)                next[now][i]=root;            else            {                fail[next[now][i]]=root;                Q[rear++]=next[now][i];            }        }        while(front<rear)        {            now=Q[front++];            for(int i=0;i<26;i++)            {                if(next[now][i]==-1)                    next[now][i]=next[fail[now]][i];///同下一样,只不过因为下个是空所以只接用next[now][i],非控就用fail来指向                else                {                    fail[next[now][i]]=next[fail[now]][i];///适配只想fail指针对应节点的相同字母处,注意是相同字母处                    Q[rear++]=next[now][i];                }            }        }    }    int Search(char buff[])    {        int now=root,res=0;        int len=strlen(buff);        for(int i=0;i<len;i++)        {            now=next[now][buff[i]-'a'];            int temp=now;            while(temp!=root)///扫描            {                res+=end[temp];                end[temp]=0;///防止重复计算                temp=fail[temp];            }        }        return res;    }    void Debug()    {        for(int i=0;i<cnt;i++)        {            printf("id=%3d fail=%3d end=%3d child=[",i,fail[i],end[i]);            for(int j=0;j<26;j++)                printf(" %3d",next[i][j]);            printf(" ]\n");        }    }};


0 0
原创粉丝点击