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;}


原创粉丝点击