3065 病毒侵袭持续中

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<set>
using namespace std;
struct node{
node * next[26];
node* fail;
int count;
node(){
count = -1;
fail = NULL;
memset(next,NULL,sizeof(next));
}
};
node *root;
char str[1100][60];
char s[2101000];
int c[1100];
void insert(char *s,int num){
node *p = root;
int l = strlen(s);
int j;
for(int i = 0;i<l;i++){
j = s[i]-'A';
if(p->next[j]==NULL)p->next[j] =new node();
p =  p->next[j];
}
p->count = num;
}
void build_fail(){
node *tmp;
queue<node*> qe;
qe.push(root);
while(!qe.empty()){
tmp = qe.front();
qe.pop();
for(int i = 0;i<26;i++){
if(tmp->next[i]!=NULL){
if(tmp==root){
tmp->next[i]->fail = root;
}else {
node *p = tmp->fail;
while(p!=NULL){
if(p->next[i]!=NULL){
tmp->next[i]->fail = p->next[i];
break;
}
p = p->fail;
}
if(p==NULL)tmp->next[i]->fail = root;
}
qe.push(tmp->next[i]);
}
}
}
}
int n;
void solve(){
memset(c,0,sizeof(c));
node *p = root;
for(int i = 0;s[i];i++){
if(s[i]>='A' && s[i]<='Z'){
int j = s[i]-'A';
while(p->next[j]==NULL && p!=root)p = p->fail;
p = p->next[j];
if(p==NULL)p = root;
node *tmp = p;
while(tmp!=NULL && tmp->count!=-1){
c[tmp->count]++;
tmp = tmp->fail;
}
}else p = root;
}
for(int i = 1;i<=n;i++){
if(c[i])printf("%s: %d\n",str[i],c[i]);
}


}
void del(node *r){
if(r==NULL)return ;
for(int i = 0;i<26;i++){
del(r->next[i]);
}
delete r;
}




int main(){
while(scanf("%d",&n)!=EOF){
root = new node();

for(int i = 1;i<=n;++i){
scanf("%s",str[i]);
insert(str[i],i);
}
build_fail();
int m;



scanf("%s",s);
solve();
}
del(root);
///printf("total: %d\n",ans_num);
return 0;
}

你可能感兴趣的:(3065 病毒侵袭持续中)