Topic Link: Click to enter
KMP the pattern string, then it is convenient to determine whether the pattern string appears in the target string, which shows that it is suitable for multiple target strings in a pattern string. But if there is more than one pattern string, then if you use KMP then you need to handle each string once, which is obviously not appropriate. In fact, this time can be all the pattern string built into a trie tree, and then a similar to the KMP method to calculate the failed pointer, it can be easily matched. In fact, this is the idea of AC automata.
The code is as follows:
#include <iostream>#include <cstdio>#include <cstring>#include <queue>using namespace STD;Const intmaxn=500000+ -;structtrie{the///next array represents the trie tree. the///fail array records the failure pointers for each node The ///end Array records the number of strings that end with the current node intnext[maxn][ -],FAIL[MAXN],END[MAXN];///root represents the root node of Trie, L represents the total number of nodes currently trie introot,l;intNewNode () { for(intI=0;i< -; i++) next[l][i]=-1; end[l++]=0;returnL-1; }voidInit () {l=0; Root=newnode (); }voidInsertCharBuf[]) {intlen=strlen(BUF);intNow=root; for(intI=0; i<len;i++) {if(next[now][buf[i]-' A ']==-1) next[now][buf[i]-' A ']=newnode (); now=next[now][buf[i]-' A ']; } end[now]++; }/// use BFS form to construct fail pointer voidBuild () { Queue<int>Q; Fail[root]=root; for(intI=0;i< -; i++) {/// If the first son of the current node does not exist ///The first son of the node failed for the current node if(next[root][i]==-1) Next[root][i]=root;Else{fail[next[root][i]]=root; Q.push (Next[root][i]); } } while(! Q.empty ()) {intNow=q.front (); Q.pop (); for(intI=0;i< -; i++) {if(next[now][i]==-1) Next[now][i]=next[fail[now]][i];Else{Fail[next[now][i]]=next[fail[now]][i]; Q.push (Next[now][i]); } } } }intQueryCharBuf[]) {intlen=strlen(BUF);intres=0;intNow=root; for(intI=0; i<len;i++) {now=next[now][buf[i]-' A '];intTemp=now; while(temp! = root) {Res+=end[temp]; end[temp]=0; TEMP=FAIL[TEMP]; } }returnRes }};Charstr[maxn*2]; Trie AC;intMain () {intTintNscanf("%d", &t); while(t--) {scanf("%d", &n); Ac.init (); for(intI=0; i<n;i++) {scanf('%s ', str); Ac.insert (str); } ac.build ();scanf('%s ', str);printf("%d\n", Ac.query (str)); }return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Hdu2222--keywords Search+ac Automaton Template