题意:
求每个模式串在母串中出现的次数
#include <map> #include <set> #include <list> #include <cmath> #include <queue> #include <stack> #include <cstdio> #include <vector> #include <string> #include <cctype> #include <complex> #include <cassert> #include <utility> #include <cstring> #include <cstdlib> #include <iostream> #include <algorithm> using namespace std; typedef pair<int,int> PII; typedef long long ll; #define lson l,m,rt<<1 #define pi acos(-1.0) #define rson m+1,r,rt<<11 #define All 1,N,1 #define read freopen("in.txt", "r", stdin) #define N 250001 const ll INFll = 0x3f3f3f3f3f3f3f3fLL; const int INF= 0x7ffffff; const int mod = 1000000007; char p[10010][25],q[25]; int n,used[N],mer[N]; struct Trie{ int ch[N][26],val[N],f[N],num; void init(){ num=1; memset(ch,0,sizeof(ch)); memset(val,0,sizeof(val)); memset(f,0,sizeof(f)); } int build(char *s){ int u=0,len=strlen(s); for(int i=0;i<len;++i) { int v=s[i]-‘a‘; if(!ch[u][v]){ memset(ch[num],0,sizeof(ch[num])); ch[u][v]=num++; } u=ch[u][v]; } val[u]++; return u; } void getfail(){ queue<int>q; for(int i=0;i<26;++i) if(ch[0][i]) q.push(ch[0][i]); while(!q.empty()){ int r=q.front(); q.pop(); for(int i=0;i<26;++i) { int u=ch[r][i]; if(!u){ch[r][i] = ch[f[r]][i];continue;} q.push(u); int v=f[r]; while(v&&!ch[v][i])v=f[v]; f[u]=ch[v][i]; } } } void find(char *T){ set<int>se; int u=0,len=strlen(T); for(int i=0;i<len;++i){ int v=T[i]-‘a‘; while(u&&ch[u][v]==0) u=f[u]; u=ch[u][v]; int tmp=u; while(tmp){ if(se.find(tmp)==se.end()){ se.insert(tmp); mer[tmp]++; } tmp=f[tmp]; } } } }ac; int main() { int n,m,hao[100010]; ac.init(); scanf("%d",&m); for(int i=1;i<=m;++i) { scanf("%s",p[i]); } scanf("%d",&n); for(int i=1;i<=n;++i){ scanf("%s",q); hao[i]=ac.build(q); } ac.getfail(); memset(mer,0,sizeof(mer)); for(int i=1;i<=m;++i){ ac.find(p[i]); } for(int i=1;i<=n;++i) printf("%d\n",mer[hao[i]]); return 0; }
LightOJ 1427 -Repository(ac自动机)
原文:http://www.cnblogs.com/zsf123/p/4780893.html