P3808 【模板】AC自动机(简单版)
作者:互联网
#include<iostream> #include<cstdio> #include<queue> #include<algorithm> #include<cmath> #include<ctime> #include<set> #include<map> #include<stack> #include<cstring> #pragma GCC optimize(2) #define inf 2147483647 #define ls rt<<1 #define rs rt<<1|1 #define lson ls,nl,mid,l,r #define rson rs,mid+1,nr,l,r #define N 1000010 #define For(i,a,b) for(int i=a;i<=b;++i) #define p(a) putchar(a) #define g() getchar() using namespace std; int n; char s[N]; namespace AC{ int tr[N][26],tot; int e[N],fail[N]; void insert(char *s){ int u=0; for(int i=1;s[i];i++){ if(!tr[u][s[i]-'a']) tr[u][s[i]-'a']=++tot; u=tr[u][s[i]-'a']; } e[u]++; } queue<int>q; void build(){ For(i,0,25) if(tr[0][i]) q.push(tr[0][i]); while(!q.empty()){ int u=q.front();q.pop(); For(i,0,25) if(tr[u][i]){ fail[tr[u][i]]=tr[fail[u]][i]; q.push(tr[u][i]); } else tr[u][i]=tr[fail[u]][i]; } } int query(char *t){ int u=0,res=0; for(int i=1;t[i];i++){ u=tr[u][t[i]-'a']; for(int j=u;j&&e[j]!=-1;j=fail[j]){ res+=e[j]; e[j]=-1; } } return res; } } void in(int &x){ int y=1;char c=g();x=0; while(c<'0'||c>'9'){if(c=='-')y=-1;c=g();} while(c<='9'&&c>='0'){ x=(x<<1)+(x<<3)+c-'0';c=g();} x*=y; } void o(int x){ if(x<0){p('-');x=-x;} if(x>9)o(x/10); p(x%10+'0'); } int main(){ in(n); For(i,1,n){ scanf("%s",s+1); AC::insert(s); } scanf("%s",s+1); AC::build(); o(AC::query(s)); return 0; }
标签:AC,int,res,tr,P3808,fail,include,模板 来源: https://www.cnblogs.com/war1111/p/11255366.html