您的位置:首页 > 其它

AC自动机模板

2013-03-08 16:31 281 查看
首先是参考胡浩大神的数组模拟指针的模板,超简洁。

View Code

#define M 57
#define N 1000007
using namespace std;

struct node
{
node *fail;
node *next[26];
int cnt;
void newnode()//生成节点
{
fail = NULL;
for (int i = 0; i < 26; ++i)
{
next[i] = NULL;
}
cnt = 0;
}
};
class Ac_Automat
{
node *q
,H
,*root;
int fr,tl,t;
public:
//    初始化
void init()
{
fr = tl = 0;
t = 0;
H[t].newnode();
root = &H[t++];
}
//    插入单词
void insert(char *s)
{
int i,k,len;
len = strlen(s);
node *p = root;
for (i = 0; i < len; ++i)
{
k = s[i] - 'a';
if (p->next[k] == NULL)
{
H[t].newnode();
p->next[k] = &H[t++];
}
p = p->next[k];
}
p->cnt++;
}
//    建立失败指针
void build()
{
root->fail = NULL;
q[tl] = root;

while (fr <= tl)
{
node *tmp = q[fr++];
node *p = NULL;
for (int i = 0; i < 26; ++i)
{
if (tmp->next[i])
{
if (tmp == root) tmp->next[i]->fail = root;
else
{
p = tmp->fail;
while (p != NULL)
{
if (p->next[i])
{
tmp->next[i]->fail = p->next[i];
break;
}
p = p->fail;
}
if (p == NULL) tmp->next[i]->fail = root;
}
q[++tl] = tmp->next[i];
}
}

}
}
//    查找
int query(char *s)
{
int res = 0;
node *p = root;
int len = strlen(s);
for (int i = 0; i < len; ++i)
{
int k = s[i] - 'a';
while (p->next[k] == NULL && p != root) p = p->fail;

p = p->next[k];
if (p == NULL) p = root;
node *tmp = p;
while (tmp != root && tmp->cnt != -1)
{
res += tmp->cnt;
tmp->cnt = - 1;
tmp = tmp->fail;
}
}
return res;
}
}ac;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: