ac自动机简介及补题二
来源:互联网 发布:java reactor设计模式 编辑:程序博客网 时间:2024/06/05 09:47
自动机我们已经介绍过了(可以看http://blog.csdn.net/invariance/article/details/78066932),所谓ac自动机就是识别串T是否能被自动机内的trie以某种方式匹配的自动机,trie可以表示多个单词。那么我们需要做的就是找到一种合适的方法缩短判断串T是否以某种方式被匹配的时间。
解法:一般的字符串算法本质上是一种奥卡姆剃刀式的算法,充分利用已有信息去减少重复的工作(空间换时间)。ac自动机也是如此,比如说在一个串上匹配到不匹配字符时,之前的子串我们已知,那么我们可以像kmp一样做一个等价转移。像kmp的next的一样,ac自动机可以建构一个fail(下面代码是用next表示子父关系的)。fail【now】表示和root到now后缀串同样的字符节点,同时是小于等于now的深度的最深的节点。所以我们可以用队列(bfs)递推的求fail,求出fail后用法和kmp的next的基本一致。
入门版题(hdu2222):
题面:
In the modern time, Search engine came into the life of everybody like Google, Baidu, etc.
Wiskey also wants to bring this feature to his image retrieval system.
Every image have a long description, when users type some keywords to find the image, the system will match the keywords with description of image and show the image which the most keywords be matched.
To simplify the problem, giving you a description of image, and some keywords, you should tell me how many keywords will be match.
解法:板题end【可以表示在该节点处结束的单词串的个数】。ans累加end。
代码:
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
using namespace std;
struct trie{
int next[500010][26],fail[500010],end[500010];
int root,l;
int newnode(){
for(int i=0;i<26;i++)
next[l][i]=-1;
end[l++]=0;
return l-1;
}
void init(){
l=0;
root=newnode();
}
void insert(char b[]){
int len=strlen(b);
int now=root;
for(int i=0;i<len;i++){
if(next[now][b[i]-'a']==-1)
next[now][b[i]-'a']=newnode();
now=next[now][b[i]-'a'];
}
end[now]++;
}
void build(){
queue<int>p;
fail[root]=root;
for(int i=0;i<26;i++)
if(next[root][i]==-1)
next[root][i]=root;
else {
fail[next[root][i]]=root;
p.push(next[root][i]);
}
while(!p.empty()){
int now=p.front();
p.pop();
for(int i=0;i<26;i++)
if(next[now][i]==-1)
next[now][i]=next[fail[now]][i];
else{
fail[next[now][i]]=next[fail[now]][i];
p.push(next[now][i]);
}
}
}
int query(char b[]){
int len=strlen(b);
int now=root;
int ans=0;
for(int i=0;i<len;i++){
now=next[now][b[i]-'a'];
int cha=now;
while(cha!=root){
ans+=end[cha];
end[cha]=0;
cha=fail[cha];
}
}
return ans;
}
};
char b[1000010];
trie ac;
int main(){
int t,n;
scanf("%d",&t);
while (t--) {
scanf("%d",&n);
ac.init();
for(int i=0;i<n;i++){
scanf("%s",b);
ac.insert(b);
}
ac.build();
scanf("%s",b);
printf("%d\n",ac.query(b));
}
return 0;
}
- ac自动机简介及补题二
- AC自动机简介
- AC自动机算法简介
- AC自动机算法及模板
- AC自动机算法及模板
- AC自动机算法及模板
- ac自动机及相关dp
- AC自动机算法简介(洛谷P3808)
- AC自动机的一些题目及思路
- AC自动机 算法 及模板
- hdu2222及易错数据(AC自动机)
- 算法讲解:ac自动机及简单衍生
- AC自动机模板及基础例题小结
- AC自动机...
- AC自动机
- AC 自动机
- AC自动机
- AC自动机
- MVC设计模式
- struts2的三种传值方式之1属性传值
- 暂存-后期再整理
- Javascript:字面量和变量
- 19个练习黑客技术的在线网站
- ac自动机简介及补题二
- 用np.maximum实现relu函数
- 欢迎使用CSDN-markdown编辑器
- 数据结构:使用栈和队列相关知识打印杨辉三角
- c++类型推导
- JSTL标准标签库
- 欢迎使用CSDN-markdown编辑器
- javascript渲染机制&运行机制&页面性能
- uva1593代码对齐