【AC自动机】【数据结构】【树】【Aho-Corasick automation】AC
引入我们首先提出一个问题: 暴力搜索这题不是sb题目吗? 样例首先我们举一个例子,我们有n=3个串he 和 her 和 she 正文概念我们使用Fail(i)表示i节点用虚线连接的边,这样的边我们的作用就是当前节点到根的路径构成的字符串的最长的存在的后缀的串的位置。比如she 和 he 中 he 就是 she 的最长的后缀所以我们连接 e2->e这样我们假设从e2无法再继续伸展的时候我们就可以O(1)找到类似的串,然后继续进行伸展得到如下的图 这样我们就构造出了一个AC自动机的图 构建方法就使用上面的例子
同时将深度为1的节点连接Fail到root
对于下面的伸展我们可以得到(同理): 代码void Insert(char *s){
int len = strlen(s),u = root;
for(int i=0;i<len;i++){
int id = idx(s[i]);
if(!pool[u].ch[id]) pool[u].ch[id] = ++ecnt;
u = pool[u].ch[id];
}
pool[u].End_Flag++;
}
void build(){
queue<int> que;
for(int i=0;i<26;i++)
if(pool[root].ch[i])
que.push(pool[root].ch[i]);
int u,v,t,p;
while(!que.empty()){
u = que.front();
que.pop();
for(int i=0;i<MAXK;i++) if(pool[u].ch[i]){
v = pool[u].ch[i];
que.push(v);
p = pool[u].Fail;
while(p && !pool[p].ch[i]) p = pool[p].Fail;
t = pool[p].ch[i];
pool[v].Fail = t;
pool[v].last = pool[t].End_Flag ? t : pool[t].last;
}
}
}
感谢感谢您阅读这篇文章,如果有不足的地方请做出评论谢谢 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |