[HihoCoder]#1036 : Trie图
来源:互联网 发布:班服t恤淘宝 编辑:程序博客网 时间:2024/06/03 02:26
华电北风吹
天津大学认知计算与应用重点实验室
2016-06-23
题目链接:
http://hihocoder.com/problemset/problem/1036
题目分析:
AC自动机模板题目。
// problem1036.cpp : 定义控制台应用程序的入口点。// http://hihocoder.com/problemset/problem/1036?sid=786734// 日期:2016-05-03#include "stdafx.h"#include <iostream>#include <queue>#include <vector>#include <string>#include <string.h>#include <fstream>using namespace std;#define size 26struct ACNode{ ACNode *fail; //失败指针 ACNode *next[size]; //Tire每个节点有26个子节点,分别对应26个英文字母 int count; //该节点是否为单词的末尾节点,也可用于判断模式是否重复 ACNode() { fail = NULL; count = 0; memset(next, NULL, sizeof(next)); }};void Insert(ACNode *root, string str){ ACNode *p = root; int i = 0, index; for (int i = 0; i < str.length(); i++) { index = str[i] - 'a'; if (p->next[index] == NULL) p->next[index] = new ACNode(); p = p->next[index]; } p->count++;}void GetFail(ACNode *root){ int i; root->fail = NULL; queue<ACNode*> q; q.push(root); while (q.empty() == false) { ACNode *temp = q.front(); q.pop(); ACNode *p = NULL; for (i = 0; i<size; i++) { if (temp->next[i] != NULL) { if (temp == root) temp->next[i]->fail = root; else { p = temp->fail; while (p != NULL) { if (p->next[i] != NULL) { temp->next[i]->fail = p->next[i]; break; } p = p->fail; } if (p == NULL) temp->next[i]->fail = root; } q.push(temp->next[i]); } } }}int Query(ACNode *root, string str){ int cnt = 0, index; ACNode *p = root; for (int i = 0; i < str.length();i++) { index = str[i] - 'a'; while (p->next[index] == NULL && p != root) p = p->fail; p = p->next[index]; p = (p == NULL) ? root : p; ACNode *temp = p; while (temp != root) { if (temp->count>0) { return true; } temp = temp->fail; } } return false;}int main(){ int n; ACNode *root = new ACNode(); cin >> n; string keyword; vector<string> keySet; for (int i = 0; i < n;i++) { cin >> keyword; keySet.push_back(keyword); Insert(root, keyword); } GetFail(root); string str; cin >> str; if (Query(root, str)) cout << "YES" << endl; else cout << "NO" << endl; return 0;}
解题报告:
直接提交报错Time Limited,第62行的while修改为if可以AC,但是这里是while才是理论上行得通的。
参考博客:
http://blog.csdn.net/zhangzhengyi03539/article/details/51302802
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
- HDU 1576 A/B 扩展欧几里得
- block,inline和inline-block概念和区别
- 2035 人见人爱A^B 快速幂取模 水题
- 关于word页眉页脚的设置-页码不连续的问题
- 创建线程的尝试
- [HihoCoder]#1036 : Trie图
- echarts-多折线图
- 1021/ Fibonacci Again 同余运算关系 + 打表 水题
- Rsync+inotify 实现文件自动同步
- String.toCharArray 方法
- LeetCode:LRU Cache
- SQL COUNT() 函数
- Android初步,JDK的配置
- hdu3826 打表《借鉴思路》