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

AC自动机模板1

时间:2019-04-06 19:02:34      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:模板   can   tps   second   register   push   return   back   put   

题目链接: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

 

AC自动机模板1

标签:模板   can   tps   second   register   push   return   back   put   

原文地址:https://www.cnblogs.com/acm1ruoji/p/10662272.html

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