标签:
题意:
给多个模式串一个母串,求个模式串在母串中出现的次数。
#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 50010 const ll INFll = 0x3f3f3f3f3f3f3f3fLL; const int INF= 0x7ffffff; const int mod = 1000000007; char str[1010][55]; int n; struct Trie{ int ch[N][26],val[N],f[N],num,hao[1010]; void init(){ num=1; memset(ch,0,sizeof(ch)); memset(val,0,sizeof(val)); memset(f,0,sizeof(f)); memset(hao,0,sizeof(hao)); } void build(char *s,int index){ 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]=index; } 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){ int u=0,len=strlen(T); for(int i=0;i<len;++i){ if(T[i]<‘A‘||T[i]>‘Z‘){ u=0; continue; } int v=T[i]-‘A‘; while(u&&ch[u][v]==0) u=f[u]; u=ch[u][v]; int tmp=u; while(tmp&&val[tmp]){ hao[val[tmp]]++; tmp=f[tmp]; } } for(int i=1;i<=n;++i){ if(hao[i]) printf("%s: %d\n",str[i],hao[i]); } } }ac; int main() { char T[2000100]; while(~scanf("%d",&n)){ ac.init(); for(int i=1;i<=n;++i){ scanf("%s",str[i]); ac.build(str[i],i); } ac.getfail(); scanf("%s",T); ac.find(T); } return 0; }
标签:
原文地址:http://www.cnblogs.com/zsf123/p/4780884.html