标签:des style blog http color io os ar java
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 35930 Accepted Submission(s): 11597
1 #define LOCAL 2 #include<cstdio> 3 #include<cstring> 4 #include<queue> 5 #include<iostream> 6 using namespace std; 7 struct Trie 8 { 9 struct Trie *fail; 10 struct Trie *child[26]; 11 int tail; //末尾标记 12 }; 13 14 void _insert(char *s,Trie *root) //构造一个Trie树 15 { 16 Trie *newcur,*cur; 17 cur=root; 18 for(int i=0;s[i];i++) 19 { 20 if(cur->child[s[i]-‘a‘]==NULL) 21 { 22 newcur= new Trie ; 23 for(int j=0;j<26;j++) 24 newcur->child[j]=NULL; 25 newcur->fail=NULL; 26 newcur->tail=0; 27 cur->child[s[i]-‘a‘]=newcur; 28 } 29 cur=cur->child[s[i]-‘a‘]; 30 } 31 cur->tail++; //有可能有重复的单词 32 } 33 34 //构造失败指针 35 void ac_fail(Trie * root) 36 { 37 queue<Trie*>tree; 38 Trie *fro,*q; 39 tree.push(root); 40 while(!tree.empty()) 41 { 42 fro=tree.front(); 43 tree.pop(); 44 for(int i=0;i<26;i++){ 45 if(fro->child[i]!=NULL) 46 { 47 if(fro==root) 48 fro->child[i]->fail=root; //将他的下一个函数的指针的失败指针指向当前指针 49 else 50 { 51 q=fro; 52 while(q->fail) 53 { 54 if(q->fail->child[i]){ 55 fro->child[i]->fail=q->fail->child[i]; 56 break; 57 } 58 q=q->fail; 59 } 60 if(!q->fail) fro->child[i]->fail=root; 61 } 62 tree.push(fro->child[i]); 63 } 64 } 65 } 66 } 67 68 int query(char *s,Trie *root) 69 { 70 Trie *cur=root,*newcur; 71 int ans=0; 72 for(int i=0;s[i];i++) 73 { 74 while(cur->child[s[i]-‘a‘]==NULL&&cur!=root) 75 cur=cur->fail; 76 cur=cur->child[s[i]-‘a‘]; 77 if(cur==NULL) cur=root; 78 newcur=cur; 79 while(newcur!=root&&newcur->tail>0) 80 { 81 ans+=newcur->tail; 82 newcur->tail=0; 83 newcur=newcur->fail; 84 } 85 } 86 return ans; 87 } 88 char s1[51]; 89 char t1[1000050]; //目标主串 90 int main() 91 { 92 #ifdef LOCAL 93 freopen("test.in","r",stdin); 94 #endif 95 int cas,n; 96 Trie *root; 97 scanf("%d",&cas); 98 while(cas--) 99 { 100 scanf("%d",&n); 101 root= new Trie; 102 for(int i=0;i<26;i++) 103 root->child[i]=NULL; 104 root->fail=NULL; 105 root->tail=0; 106 while(n--) 107 { 108 scanf("%s",s1); 109 _insert(s1,root); 110 } 111 ac_fail(root); 112 scanf("%s",t1); 113 printf("%d\n",query(t1,root)); 114 } 115 return 0; 116 }
hdu----(2222)Keywords Search(ac自动机)
标签:des style blog http color io os ar java
原文地址:http://www.cnblogs.com/gongxijun/p/4012488.html