Test instructions: Give you some words in advance, and then give you a string that determines how many words appear in the string.
Analysis: Solved using AC automata. Here are the templates that you write yourself. can be used directly. Finally, remember to release the memory.
#include <iostream> #include <queue>using namespace std, #define Letter_count 26class ac_automation{private : struct node{node* fail; Failed pointer node* Next[letter_count]; Tire the child node of the tree node int count; Is the last node of the word () {Fail=null;count=0;memset (next,null,sizeof (next));}}; node* m_sroot;void Delete (node* p);p ublic:ac_automation () {m_sroot= (node*) new Node ();} ~ac_automation () {Delete (m_sroot);} void Addword (char* str); Add a word void build_ac_automation (); int getmatchingcount (char* str);}; int Ac_automation::getmatchingcount (char* str) {int cnt=0,index; node* P,*temp;p=m_sroot;while (*str) {index=*str-' a '; while (P->next[index]==null && p!=m_sroot) p=p-> Fail;p=p->next[index];p = (p==null)? M_sroot:p;temp=p;while (Temp!=m_sroot && temp->count!=-1)// Make sure all the words that precede the current character are matched with {cnt+=temp->count;temp->count=-1;temp=temp->fail;} str++;} return CNT;} void Ac_automation::D elete (node* p) {for (int i=0;i<letter_count;i++) if (P->next[i]!=nulL) Delete (P->next[i]);d elete p;} void Ac_automation::build_ac_automation () {int i; Node *temp,*p;queue<node*> Q; Queue, for BFS, build failed pointer M_sroot->fail=null;q.push (m_sroot), while (!q.empty ()) {Temp=q.front (); Q.pop ();p =null;for (i=0 ; i<letter_count;i++) {if (temp->next[i]!=null) {if (temp==m_sroot) temp->next[i]->fail=m_sroot;else{p= Temp->fail;while (p!=null) {if (p->next[i]!=null) {temp->next[i]->fail=p->next[i];break;} P=p->fail;} if (p==null) temp->next[i]->fail=m_sroot;} Q.push (Temp->next[i]); Child nodes such as Queues}}}}void Ac_automation::addword (char* str) {node* p=m_sroot;int i=0;int index;while (*str) {index=*str-' a '; P->next[index]==null) p->next[index]= (node*) New Node ();p =p->next[index];str++;} p->count++; The last node of the word is added 1, and a single table adds a new word}int main () {int T,n,i;char A[51];char b[1000001];cin>>t;while (t--) {ac_automation ac_ Auto;cin>>n;for (i=0;i<n;i++) {Cin>>a;ac_auto. Addword (a);} Ac_auto. Build_ac_automation (); cin>>b;cout<< Ac_auto. Getmatchingcount (b) <<endl;} return 0;}
HDU ACM 2222->ac Automatic template problem (entry question)