标签:
题意:
给定多个模式串,每给一个母串,输出包含模式串的编号,最后输出包含模式串的母串的数量。
分析:
ac自动机模板
#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 60010 const ll INFll = 0x3f3f3f3f3f3f3f3fLL; const int INF= 0x7ffffff; const int mod = 1000000007; int ans[3]; struct Trie{ int ch[N][95],val[N],f[N],num; void init(){ num=1; memset(ch,0,sizeof(ch)); memset(val,0,sizeof(val)); memset(f,0,sizeof(f)); } void build(char *s,int index){ int u=0,len=strlen(s); for(int i=0;i<len;++i) { int v=s[i]-32; if(!ch[u][v]){ memset(ch[num],0,sizeof(ch[num])); ch[u][v]=num++; } u=ch[u][v]; } val[u]=index; } void getfail(){ queue<int>q; for(int i=0;i<95;++i) if(ch[0][i]) q.push(ch[0][i]); while(!q.empty()){ int r=q.front(); q.pop(); for(int i=0;i<95;++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]; } } } int find(char *T,int index){ int u=0,len=strlen(T),num=0; for(int i=0;i<len;++i){ int v=T[i]-32; while(u&&ch[u][v]==0) u=f[u]; u=ch[u][v]; int tmp=u; while(tmp&&val[tmp]){ if(!num)printf("web %d:", index); ans[num++]=val[tmp]; if(num==3)break; tmp=f[tmp]; } } if(num){ sort(ans, ans+num); int len=unique(ans,ans+num)-ans; for(int k = 0; k < len; k++)printf(" %d",ans[k]); printf("\n"); } return num>0; } }ac; int main() { char s[210],T[10100]; int n,m; scanf("%d",&n); getchar(); ac.init(); for(int i=1;i<=n;++i){ scanf("%s",s); ac.build(s,i); } ac.getfail(); scanf("%d",&m); getchar(); int total=0; for(int i=1;i<=m;++i){ scanf("%s",T); total+=ac.find(T,i); } printf("total: %d\n",total); return 0; }
标签:
原文地址:http://www.cnblogs.com/zsf123/p/4780882.html