HDOJ 2222 Keywords Search
刚学完AC自动机拿来练手的题 纯模板题
附一个讲解自动机的不错的博客:http://blog.csdn.net/niushuai666/article/details/7002823
结合本题可加深理解
普通指针版
#include
#include
#include
using namespace std;
typedef struct node
{
int count;
node* fail;
node* next[26];
node()
{
count=0;
fail=NULL;
for(int i=0;i<26;++i)
next[i]=NULL;
}
}*Pnode;
Pnode insert(Pnode root,string s)
{
Pnode p=root;
int len=s.size();
for(int i=0;i
next[s[i]-'a'])
p->next[s[i]-'a']=new node();
p=p->next[s[i]-'a'];
}
p->count++;
return root;
}
void build_AC(Pnode root)
{
Pnode p,temp;
queue
q; q.push(root); while(!q.empty()) { p=q.front(); q.pop(); for(int i=0;i<26;++i) if(p->next[i]) { if(p==root) p->next[i]->fail=root; else { temp=p->fail; while(temp) { if(temp->next[i]) { p->next[i]->fail=temp->next[i]; break; } temp=temp->fail; } if(!temp) p->next[i]->fail=root; } q.push(p->next[i]); } } } int match(Pnode root,string s) { int result=0,len=s.size(); Pnode p=root,temp; for(int i=0;i
next[s[i]-'a']&&p!=root) p=p->fail; p=p->next[s[i]-'a']; if(!p) p=root; temp=p; while(temp!=root&&temp->count!=-1) { result+=temp->count; temp->count=-1; temp=temp->fail; } } return result; } int main() { int t,n; string keyword,s; Pnode root; cin>>t; while(t--) { root=new node(); cin>>n; while(n--) { cin>>keyword; root=insert(root,keyword); } build_AC(root); cin>>s; cout<
<
前向星版
#include
#include
#include
#include
#include
using namespace std; typedef struct Node { int ch[26],fail,cnt; }Node; Node nd[555555]; int tp; void CreateNode(int t) { nd[t].fail = -1; nd[t].cnt = 0; for(int i = 0; i < 26; ++i) nd[t].ch[i] = -1; } void Insert(int root,char *str) { int i,k; for(i = 0; str[i]; ++i) { k = nd[root].ch[str[i]-'a']; if(k == -1) { nd[root].ch[str[i]-'a'] = tp; CreateNode(tp); root = tp++; }else root = k; } nd[root].cnt++; } void Build_AC(int root) { queue
q; q.push(root); int i,temp; while(!q.empty()) { root = q.front(); q.pop(); for(i = 0; i < 26; ++i) { if(nd[root].ch[i] != -1) { if(!root) nd[nd[root].ch[i]].fail = 0; else { temp = nd[root].fail; while(temp && nd[temp].ch[i] == -1) temp = nd[temp].fail; nd[nd[root].ch[i]].fail = (nd[temp].ch[i] == -1)? temp: nd[temp].ch[i]; } q.push(nd[root].ch[i]); } } } } int Search(int root,char *str) { int cnt = 0,temp,i; for(i = 0; str[i]; ++i) { while(root && nd[root].ch[str[i]-'a'] == -1) root = nd[root].fail; root = nd[root].ch[str[i]-'a']; if(root == -1) root = 0; temp = root; while(temp && nd[temp].cnt != -1) { cnt += nd[temp].cnt; nd[temp].cnt = -1; temp = nd[temp].fail; } } return cnt; } int main() { int t,n; char str[1111111]; scanf("%d",&t); while(t--) { tp = 1; CreateNode(0); scanf("%d",&n); while(n--) { scanf("%s",str); Insert(0,str); } Build_AC(0); scanf("%s",str); printf("%d\n",Search(0,str)); } return 0; }