Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 19868 Accepted Submission(s): 6669
1 #include<iostream> 2 using namespace std; 3 4 struct node 5 { 6 node *fail; 7 node *next[26]; 8 int count; 9 node() 10 { 11 fail=NULL; 12 count=0; 13 memset(next,NULL,sizeof(next)); 14 } 15 }*q[500001]; 16 17 char keyword[55]; 18 char str[1000010]; 19 20 void insert(char *str,node *root) 21 { 22 node *p=root; 23 int i=0; 24 while(str[i]) 25 { 26 int index=str[i]-'a'; 27 if(p->next[index]==NULL) 28 p->next[index]=new node(); 29 p=p->next[index]; 30 i++; 31 } 32 p->count++; 33 } 34 35 void acbuild(node *root) //构建失败指针 36 { 37 int i; 38 int head=0,tail=0; 39 root->fail=NULL; 40 q[tail++]=root; 41 while(head!=tail) 42 { 43 node *temp=q[head++]; 44 node *p=NULL; 45 for(i=0;i<26;i++) 46 { 47 if(temp->next[i]!=NULL) 48 { 49 if(temp==root) 50 temp->next[i]->fail=root; 51 else 52 { 53 p=temp->fail; 54 while(p!=NULL) 55 { 56 if(p->next[i]!=NULL) 57 { 58 temp->next[i]->fail=p->next[i]; 59 break; 60 } 61 p=p->fail; 62 } 63 if(p==NULL) 64 temp->next[i]->fail=root; 65 } 66 q[tail++]=temp->next[i]; 67 } 68 } 69 } 70 } 71 72 int query(node *root) 73 { 74 int i=0,cnt=0; 75 int index; 76 node *p=root; 77 while(str[i]) 78 { 79 index=str[i]-'a'; 80 while(p!=root&&p->next[index]==NULL) 81 p=p->fail; 82 p=p->next[index]; 83 p=(p==NULL)?root:p; 84 node *temp=p; 85 while(temp!=root&&temp->count!=-1) 86 { 87 cnt+=temp->count; 88 temp->count=-1; 89 temp=temp->fail; 90 } 91 i++; 92 } 93 return cnt; 94 } 95 96 int main() 97 { 98 int n,t; 99 scanf("%d",&t); 100 while(t--) 101 { 102 node *root=new node(); 103 scanf("%d",&n); 104 getchar(); 105 for(int i=0;i<n;i++) 106 { 107 gets(keyword); 108 insert(keyword,root); 109 } 110 acbuild(root); 111 scanf("%s",str); 112 printf("%d\n",query(root)); 113 } 114 return 0; 115 } 116 /* 117 10 118 3 119 a 120 bb 121 ca 122 aabbcca 123 */