hihoCoder #1036 Trie图
来源:互联网 发布:二手索尼z3淘宝 编辑:程序博客网 时间:2024/05/20 23:30
传送门:点击打开链接
自动机即在Trie树中利用KMP算法的next数组进行优化搜索,并且利用了BFS进行遍历建树
在建树时不能用for循环遍历26个字母,否则会超时,TL的教训
每走到一个节点,计算它的后缀节点和该节点表示的字符串加上任一字符后所生成的字符串
#include<iostream>#include<algorithm>#include<cstring>#include<stdio.h>#include<queue>using namespace std;int n;char s[1000005];struct node{node *son[26];//二十六个子节点node *next;//后缀节点bool end_;node():end_(false), next(NULL){memset(son, NULL, sizeof(son));}};node *root;void insert(char *c){int index;node *tree = root;while(*c)//用for循环遍历26个字母会超时{index = *c - 'a';if(tree -> son[index] == NULL)//没有子节点则直接新建一个子节点{tree -> son[index] = new node();}tree = tree -> son[index];//指向刚添加的子节点++c;}tree -> end_ = true;//对每个字符串的结尾进行标记表示已经结束}void build(){queue<node *> que;node *tree = root;for(int i = 0; i < 26; i++){if(root -> son[i] != NULL)//当存在有该字母的边连接的子节点{tree -> son[i] -> next = root;//根节点的所有子节点的后缀节点都是根节点que.push(tree -> son[i]);//利用BFS进行遍历}}while(!que.empty()){tree = que.front();que.pop();for(int i = 0; i < 26; i++){if(tree -> son[i] != NULL)//存在对应字母的节点{while(tree -> next != NULL)//后缀节点不为空{if(tree -> next -> son[i] != NULL){tree -> son[i] -> next = tree -> next -> son[i];//子节点的后缀节点为父节点的后缀节点加子节点比父节点多的字母if(tree -> next -> son[i] -> end_)tree -> son[i] -> end_ = true;//后缀节点为标记节点的节点也需要被标记 即字符串结束的标记break;//当前字母成功匹配,退出循环,比较下一个字符}tree -> next = tree -> next -> next;}if(tree -> son[i] -> next == NULL)//若无对应的后缀节点则将root作为后缀节点tree -> son[i] -> next = root;que.push(tree -> son[i]);}}}}bool check(char *c){int index;node *tree = root;while(*c){index = *c - 'a';while(tree != NULL){if(tree -> son[index] != NULL){tree = tree -> son[index];if(tree -> end_ == true)return true;break;}tree = tree -> next;}if(tree == NULL)//图中不存在该字符,则从root开始重新查找tree = root;++c;}return false;}int main(){root = new node();bool ans;cin>>n;while(n--){cin>>s;insert(s);}build();cin>>s;ans = check(s);if(ans)cout<<"YES"<<endl;elsecout<<"NO"<<endl;return 0;}
阅读全文
0 0
- hihocoder #1036 : Trie图
- [HihoCoder]#1036 : Trie图
- #hihocoder 1036 trie图
- hihoCoder #1036 Trie图
- hihoCoder #1036 : Trie图 (AC自动机)
- hihoCoder 1036 Trie图(AC自动机)
- HiHocoder 1036 : Trie图 AC自动机
- hihoCoder--1036 Trie图(AC自动机)
- hihoCoder 1036 AC自动机 Trie图
- hihoCoder 1036 Trie图 AC自动机
- hihocoder-1036 Trie图(Trie图||AC自动机)
- hihoCoder:Trie图
- HihoCoder第四周:Trie图
- hiho一下 第四周 Hihocoder #1036 : Trie图
- hihocoder Trie图(AC自动机)
- HihoCoder第四周(Trie图)
- hihocoder 1014 Trie树 trie
- [hihoCoder 1014][Trie 树]Trie
- 光学设计CAD:基于ZEMAX的望远物镜优化设计
- cmake编译Debug和Release版本的注意点
- NoSQL 数据库索引 总结
- linux用户与用户组管理
- 索引器概述
- hihoCoder #1036 Trie图
- 算法--组合数学:杨辉三角数学分析以及Java实现
- LeetCode 207 Course Schedule 题解
- ios开发遇到的分辨率问题
- NOIP2017模拟赛(1) 总结
- java.lang.ClassNotFoundException: com.microsoft.jdbc.sqlserver.SQLServerDriver的问题
- 之江学院第0届校赛决赛 F-qwb has a lot of Coins
- libyuv—AndroidStudio 编译libyuv
- VRTK: 使用触摸板移动