Question Link: Http://acm.hdu.edu.cn/showproblem.php? PID = 1, 2222
Theme: Multiple mode strings. How many pattern strings are contained in the matching string. Note that the mode strings are repeated, so the results must be repeated cumulatively.
Solutions:
The template of the AC automatic machine.
The static lrj template does not support repeated mode strings.
In the process of creating an AC automatic machine + dp, I found the zcwwzdjn's dynamic optimization (not matching to the root) method, and used the online AC automatic machine template as a reference,
This template supports repeated strings.
#include "cstdio"#include "cstring"#include "iostream"#include "queue"#include "string"using namespace std;struct Trie{ Trie *next[26],*fail; int cnt;}*root;Trie *newnode(){ Trie *ret=new Trie; memset(ret->next,0,sizeof(ret->next)); ret->fail=0; ret->cnt=0; return ret;}void init() {root=newnode();}void Insert(string str){ Trie *pos=root; for(int i=0;i<str.size();i++) { int c=str[i]-‘a‘; if(!pos->next[c]) pos->next[c]=newnode(); pos=pos->next[c]; } pos->cnt++;}void getfail(){ queue<Trie *> Q; for(int c=0;c<26;c++) { if(root->next[c]) { root->next[c]->fail=root; Q.push(root->next[c]); } else root->next[c]=root; } while(!Q.empty()) { Trie *x=Q.front();Q.pop(); for(int c=0;c<26;c++) { if(x->next[c]) { x->next[c]->fail=x->fail->next[c]; Q.push(x->next[c]); } else x->next[c]=x->fail->next[c]; } }}int find(string str){ Trie *pos=root,*last; int ans=0; for(int i=0;i<str.size();i++) { int c=str[i]-‘a‘;last; if(pos->next[c]) { pos=pos->next[c]; last=pos; while(last->cnt) { ans+=last->cnt; last->cnt=0; last=last->fail; } } } return ans;}int main(){ //freopen("in.txt","r",stdin); ios::sync_with_stdio(false); int T,n; string tt; cin>>T; while(T--) { cin>>n; init(); for(int i=1;i<=n;i++) { cin>>tt; Insert(tt); } getfail(); cin>>tt; int ans=find(tt); printf("%d\n",ans); }}
11927003 |
2014-10-21 01:22:37 |
Accepted |
2222 |
390 Ms |
29480 K |
1942 B |
C ++ |
Physcal |
HDU 2222 (AC automatic machine template)