您的位置:首页 > 其它

AC自动机总结 与模板题

2016-03-19 20:25 465 查看
参考学习资料:http://blog.csdn.net/niushuai666/article/details/7002823

学会trie树和kmp算法后就可以学习ac自动机了。

ac自动机可以用于多个模式串的匹配问题上。比如考虑在一个文本中出现了几个所给出的模式串。

整个结构大致跟trie树一样,不过多加了个fail指针,这个思想跟KMP算法是类似的,就是防止主串的回退,使当前字符失配时跳转到具有最长公共前后缀的字符继续匹配。

ac自动机的构建:

1)构造trie树,定义数据结构。

2)设置fail指针,使当前字符失配时跳转到具有最长公共前后缀的字符继续匹配,在失配的时候利用fail指针进行跳转,跳转后串的前缀,与跳转前串的后缀肯定是一样的。而且跳转后的位置得深度(就是匹配字符的个数)一定是小于之前的节点的。利用这个用bfs来构造fail指针。

构造trie树:

也就是插入每个模式串,跟之前的trie树基本一样,没什么好说的,就是在处理上,我们是要找到跟模式串完全一样的,所以只有在最后的时候才计数。

构造fail指针:

利用bfs,root 的fail指针就是NULL, 将root先压入队列,每次从队列中取出一个节点,取出来的节点的fail指针一定都已经构造好了,此时需要构造该节点的儿子节点的fail指针。如果这个节点就是root,那么他所有儿子的fail指针都是指向root。因为root不代表任何一个字符。如果不是的话,构造这个儿子节点的fail指针的时候要用到父亲的fail指针,并从父亲fail指针指向的地方走下去

1)如果有跟当前字符一样的子节点,就将要构造的那个fail指针指向它,结束。

2)如果没有的话就将那个父亲的fail指针,递归上去找再之前的fail指针,然后重复1),如果指到了NULL也没有,那么也结束,并将这个fail指针指向root。

3)将这个儿子节点压入队列

扫描主串:

两种情况:

1)如果当前字符匹配,表示从当前节点沿着树边有一条路径可以到达目标字符。走向下一个节点继续匹配。

2)如果不匹配,去当前节点失败指针所指向的字符继续匹配,直到变成1),或者指向了root。

重复1)2) 直到主串扫描完成。

模板题:

hdu 2222

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
#define M 26
int n;
char s1[100009],s[1000009];
struct node
{
node* fail;
node* next[M];
int cnt;
node() //构造函数
{
fail = NULL;
memset(next,NULL,sizeof(next));
cnt = 0;
}
};
void insert_ac(char* p,node* root)
{
node* tmp = root;
int l = strlen(p);
for(int i = 0;i < l;i++)
{
int k = p[i] - 'a';
if(tmp->next[k] == NULL) tmp->next[k] = new node();
tmp = tmp->next[k];
}
tmp->cnt++;
}
void build_fail(node* root)
{
queue<node*> q;
q.push(root);
while(!q.empty())
{
node* tmp = q.front();
q.pop();
node* p = NULL;
for(int i = 0;i < M;i++) //构造tmp->next[i]的fail指针
{
if(tmp->next[i] != NULL) //出现过
{
if(tmp == root) tmp->next[i]->fail = root;
else
{
p = tmp->fail; //父节点的fail指针
while(p != NULL)
{
if(p->next[i] != NULL) //有跟该字符一样的
{
tmp->next[i]->fail = p->next[i]; //将fail指针指向那个位置
break;
}
p = p->fail;
}
if(p == NULL) tmp->next[i]->fail = root;
}
q.push(tmp->next[i]);
}
}
}
}
int search_ac(char* s,node* root)
{
int ans = 0;
int l = strlen(s);
node* p = root;
for(int i = 0;i < l;i++)
{
int index = s[i] - 'a';
while(p->next[index] == NULL && p != root) p = p->fail; //如果不匹配去失败指针指向的字符继续匹配,直到匹配或者到root
p = p->next[index];
if(p == NULL) p = root;
node* tmp = p;
while(tmp != root && tmp->cnt != -1) //根据题目意思防止同一个模式串记了两次
{
ans += tmp->cnt;
tmp->cnt = -1;
tmp = tmp->fail;
}
}
return ans;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
node* root = new node();
while(n--)
{
scanf("%s",s1);
insert_ac(s1,root);
}
build_fail(root);
scanf("%s",s);
printf("%d\n",search_ac(s,root));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: