[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