zoukankan      html  css  js  c++  java
  • AC自动机模板1

    题目链接:https://www.luogu.org/problemnew/show/P3808

    要注意的是一定要把len赋值strlen(s);不然超时超的自闭!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    #include <bits/stdc++.h>
    using namespace std;
    #define ll long long
    #define re register
    #define fi first
    #define se second
    #define mp make_pair
    #define pb push_back
    #define P pair<int,int>
    const int N=1e6+10;
    void read(int &a)
    {
        a=0;
        int d=1;
        char ch;
        while(ch=getchar(),ch>'9'||ch<'0')
            if(ch=='-')
                d=-1;
        a=ch-'0';
        while(ch=getchar(),ch>='0'&&ch<='9')
            a=a*10+ch-'0';
        a*=d;
    }
    void write(int x)
    {
        if(x<0)
            putchar(45),x=-x;
        if(x>9)
            write(x/10);
        putchar(x%10+'0');
    }
    struct note
    {
        int to[30],bz,nex;
    }trie[N];
    int tot;
    char s[N];
    void ins(char *s)
    {
        int t=0;
        int len=strlen(s);
        for(re int i=0;i<len;i++)
        {
            int x=s[i]-96;
            if(!trie[t].to[x])
                trie[t].to[x]=++tot;
            t=trie[t].to[x];
        }
        trie[t].bz++;
    }
    void built()
    {
        queue <int> q;
        for(re int i=1;i<=26;i++)
            if(trie[0].to[i])
                trie[trie[0].to[i]].nex=0,q.push(trie[0].to[i]);
        while(!q.empty())
        {
            int p=q.front();
            q.pop();
            for(re int i=1;i<=26;i++)
                if(trie[p].to[i])
                    trie[trie[p].to[i]].nex=trie[trie[p].nex].to[i],q.push(trie[p].to[i]);
                else
                    trie[p].to[i]=trie[trie[p].nex].to[i];
        }
    }
    int solve(char *s)
    {
        int ans=0,now=0;
        int len=strlen(s);
        for(re int i=0;i<len;i++)
        {
            now=trie[now].to[s[i]-'a'+1];
            for(re int j=now;j&&trie[j].bz!=-1;j=trie[j].nex)
                ans+=trie[j].bz,trie[j].bz=-1;
        }
        return ans;
    }
    int main()
    {
        int n;
        read(n);
        while(n--)
        {
            scanf("%s",s);
            ins(s);
        }
        trie[0].nex=0;
        built();
        scanf("%s",s);
        cout<<solve(s)<<endl;
        return 0;
    }
    View Code
  • 相关阅读:
    ACMer第7天Falling Ants
    贪心初步-FatMouse' Trade
    贪心初步-A
    ACM集训第二天
    asp.net中遍历套用母版页的页面的控件
    a 标签中调用js的几种方法
    笔记
    html控件和web控件
    ASP.NET中GUID类
    (转)常见邮件服务器(接收服务器和发送邮件服务器)地址
  • 原文地址:https://www.cnblogs.com/acm1ruoji/p/10662272.html
Copyright © 2011-2022 走看看