标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 9831 Accepted Submission(s): 3457
#include<cstdio> #include<cstring> #include<queue> using namespace std; const int MAXN=500005; const int N=128; int n; int Hash[1005]; struct ID{ char ss[55]; ID() { memset(ss,0,sizeof(ss)); } }words[1005]; struct Trie{ int next[MAXN][N],fail[MAXN],end[MAXN]; int tot,root,id; int newnode() { for(int i=0;i<N;i++) next[tot][i]=-1; end[tot++]=0; return tot-1; } void init() { tot=0; root=newnode(); } void insert(char buf[],int id) { int len=strlen(buf); int now=root; for(int i=0;i<len;i++) { int k=buf[i]; if(next[now][k]==-1) next[now][k]=newnode(); now=next[now][k]; } end[now]=id; } void build() { fail[root]=root; queue<int> que; for(int i=0;i<N;i++) if(next[root][i]==-1) next[root][i]=root; else { fail[next[root][i]]=root; que.push(next[root][i]); } while(!que.empty()) { int now=que.front(); que.pop(); for(int i=0;i<N;i++) if(next[now][i]==-1) next[now][i]=next[fail[now]][i]; else { fail[next[now][i]]=next[fail[now]][i]; que.push(next[now][i]); } } } void query(char buf[]) { int len=strlen(buf); int now=root; for(int i=0;i<len;i++) { now=next[now][buf[i]]; int temp=now; while(temp!=root) { if(end[temp]!=0) Hash[end[temp]]++; //若每个模式串只在主串中匹配一次则加上 end[temp]=0; temp=fail[temp]; } } for(int i=1;i<=n;i++) { if(Hash[i]!=0) { printf("%s: %d\n",words[i].ss,Hash[i]); } } } }; Trie ac; char buf[2000005]; int main() { while(scanf("%d",&n)!=EOF) { memset(Hash,0,sizeof(Hash)); ac.init(); for(int i=1;i<=n;i++) { scanf("%s",words[i].ss); ac.insert(words[i].ss,i); } ac.build(); scanf("%s",buf); ac.query(buf); } return 0; }
标签:
原文地址:http://www.cnblogs.com/program-ccc/p/5210694.html