标签:
按以下格式每行一个,输出每个病毒出现次数。未出现的病毒不需要输出。
#include<iostream> #include<cstdio> #include<cstring> #define MAXC 26 #define MAXS 1002 #define MAXN 2000005 #define MAXL 51 char word[MAXS][MAXL],web[MAXN]; struct node { int nxt[MAXC],fail,id; void clear() { memset(nxt,0,sizeof nxt); fail=0,id=0; } }trie[MAXL*MAXS]; int myq[MAXL*MAXS],head,tail,root,tot=1,ans[MAXS],n; void insert(int r,char *s,int id) { int len=strlen(s); for(int i=0;i<len;i++) { if(trie[r].nxt[s[i]-‘A‘]==0) {trie[r].nxt[s[i]-‘A‘]=++tot; trie[tot].clear(); } r=trie[r].nxt[s[i]-‘A‘]; } trie[r].id=id; } void build(int r) { trie[r].fail=r; myq[tail++]=r; int ch; while(head<tail) { r=myq[head++]; if(r==root) { for(int i=0;i<MAXC;i++) { if(trie[r].nxt[i]==0) trie[r].nxt[i]=root; else {myq[tail++]=trie[r].nxt[i]; trie[trie[r].nxt[i]].fail=root; } } } else { for(int i=0;i<MAXC;i++) { ch=trie[r].nxt[i]; if(ch) { myq[tail++]=ch; if(trie[trie[r].fail].nxt[i]!=ch) trie[ch].fail=trie[trie[r].fail].nxt[i]; else trie[ch].fail=root; } else trie[r].nxt[i]=trie[trie[r].fail].nxt[i]; } } } } void query(int r,char *s) { int len=strlen(s),failp,val; for(int i=0;i<len;i++) { val=s[i]-‘A‘; if(val<0||val>25) {r=root;continue;} r=trie[r].nxt[val]; for(failp=r;failp!=root;failp=trie[failp].fail) if(trie[failp].id) ans[trie[failp].id]++; } } int main() { while(~scanf("%d",&n)) { root=1;tot=1; head=tail=0; memset(ans,0,sizeof ans); trie[root].clear(); for(int i=0;i<n;i++) { scanf("%s",word[i]); insert(root,word[i],i+1); } build(root); scanf("%s",web); query(root,web); for(int i=1;i<=n;i++) { if(ans[i]) printf("%s: %d\n",word[i-1],ans[i]); } } }
标签:
原文地址:http://www.cnblogs.com/hefenghhhh/p/5064199.html