zoukankan      html  css  js  c++  java
  • P3808 【模板】AC自动机(简单版)

    题意:给出n个模式串和一个文本串,问在文本串中出现了几个模式串。

    思路:AC自动机裸题;

    看过n个版本的AC自动机后终于理解了代码是如何实现的。再一次体会到光懂得原理和能利用原理解决问题之间的巨大的鸿沟。

    代码:

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    #include <vector>
    #include <queue>
    #define INF 0x3f3f3f3f
    #define FRE() freopen("in.txt","r",stdin)
    using namespace std;
    const int maxn = 1e6+10;
    typedef long long ll;
    typedef pair<int,int> P;
    int cnt = 0;
    struct AC
    {
        int next[26];
        int en,fail;
    }ac[maxn];
    
    void Build(char* str)//建字典树
    {
        int rt = 0;
        for(int i = 0; str[i]; i++)
        {
            int index = str[i] - 'a';
            if(!ac[rt].next[index])
                ac[rt].next[index] = ++cnt;
            rt = ac[rt].next[index];
        }
        ac[rt].en++;
    }
    
    void getFail()//获取fail指针
    {
        queue<int> que;
        for(int i = 0; i < 26; i++)
        {
            if(ac[0].next[i])
            {
                ac[ac[0].next[i]].fail = 0;//将根节点孩子的fail指针指向根,即0
                que.push(ac[0].next[i]);
            }
        }
        while(!que.empty())
        {
            int now = que.front(); que.pop();
            for(int i = 0; i < 26; i++)
            {
                if(!ac[now].next[i])//如果该节点孩子没有出现过,就将这个节点的孩子等于该节点fail指向的节点的孩子
                    ac[now].next[i] = ac[ac[now].fail].next[i];
                else//出现过就将这个节点孩子的fail指向这个节点的fail指向的节点的孩子
                {
                    ac[ac[now].next[i]].fail = ac[ac[now].fail].next[i];
                    que.push(ac[now].next[i]);
                }
            }
        }
    }
    
    int Fun(char* str)
    {
        int rt = 0,res = 0;
        for(int i = 0; str[i]; i++)
        {
            rt = ac[rt].next[str[i]-'a'];
            for(int j = rt; j&&ac[j].en!=-1; j= ac[j].fail)
            {
                res += ac[j].en;
                ac[j].en = -1;
            }
        }
        return res;
    }
    
    char buf[maxn];
    int main()
    {
    
        int t;
        scanf("%d",&t);
        while(t--)
        {
            scanf("%s",buf);
            Build(buf);
        }
        getFail();
        scanf("%s",buf);
        printf("%d
    ",Fun(buf));
        return 0;
    }
    View Code
  • 相关阅读:
    Silverlight4 GDR3与Silverlight5 EAP1的变化
    使用微软WPF技术开发产品优势究竟在那里
    于娟——《活着就是王道》博客精华文摘
    Silverlight中开发和设计人员的合作
    ubuntu10.10编译内核步骤
    添加系统调用实验步骤
    SinaWeiboSdk c++test
    【转】windows7下硬盘安装linux,双系统共存
    cppunit在vs2008下使用的环境搭建(上)
    【转】RedHat Linux 5 安装 OpenOffice 3.2.0
  • 原文地址:https://www.cnblogs.com/sykline/p/9737770.html
Copyright © 2011-2022 走看看