Hihocoder #1036: trie diagram (AC automaton)

Source: Internet
Author: User

#1036: Trie Chart
Time limit:20000msSingle Point time limit:1000msMemory Limit:512MB
Description previously Review

On the last mention, Little Hi and Little Ho received the great and glorious task of Mr. Crab: Mr. Crab will give them an article collected from the Internet, and a thick river crab dictionary, and what they want to do is to judge whether there are those words in this article that belong to the river Crab dictionary.

At the time, Little Hi and Little ho were still very limited, and they could only think:"Enumerate each word, then enumerate the possible starting positions in the article, and then match them to see if they are successful." " such a very simple idea, but this algorithm time complexity is quite high, if the dictionary word number is n, each word length is l, the length of the article is M, then the number of calculations that need to be performed at n*m*l this level , And this data is not acceptable to Mr. Crab.

So Mr. Crab decided to give them a chance to study first, so gave a condition n=1, that is, the dictionary is actually only a word, but I hope they can count the number of words in the article, this is what we often say pattern matching problem. and small hi and small ho, through this week's efforts, learning to delve into the KMP algorithm, and help each other, has successfully solved the problem!

This is what happened in the third week of Hiho, and now the four thoughtful, small hi and small ho also embark on the journey to solve the real problem!

Mission Review

Small hi and small ho is a pair of good friends, born in the information society, they have a great interest in programming, they agreed to help each other, in the programming of learning along the road together.

This day, they ... Cough, said far, say then small Ho finally finished the third week program, but found that he missed the Hihocoder on the submission date, so find small hi cry, small hi although as an administrator, but also bad broken This example, so small ho to the question bank handed the code, finally is coax good small ho.

Small HO after the program and then fart back to the small hi side, asked: "Little Hi, you say we can go to complete the river Crab big task?" ”

Small hi think half a day, way: "The night view of the stars ... Ah no, I looked at a lot of information these two days, found that this problem is also a very classic problem, as early as 06 in the national training team of the Olympic Games of informatics perfect detail analysis of this problem, and they use is trie figure such a data structure! ”

"Trie map?" Is it similar to the trie tree we met in the second week? Little Ho asked.

Yes Trie graph is a kind of data structure developed on the basis of trie tree. If you want to use a dictionary to form a trie diagram, then first use this dictionary to form a trie tree, and then add some sides on the basis of trie tree, you can become a trie map! "Small hi and teacher-like."

Oh But you said so much, I do not know what the trie map is! "Little ho helpless Way."

Is So let's start from the beginning, talk about how to solve the problem with the trie tree, and then, on the basis of the trie tree, discuss what to do next. "Little Hi wanted to say."

Tip One: How to use trie tree for "crab"

"Now we have a time-complexity method at O (ML) level, but our journey is in the stars of the sea, ah no, we can't be content with such a 60-point approach." So, we still have to follow our usual approach, looking for those redundant computations in this algorithm ! "Little Hi Way:" Then we now see what happens when the trie tree is calculated. ”

Hint two: The optimization idea of trie tree--suffix node

"So now ..." little hi was just about to open up and was interrupted by Little ho.

"But little Hi teacher ~ you see in this case, node C can not find the corresponding suffix node, it corresponds to the path is AAABC, and AABC in trie inside is not out!" Little Ho waved a piece of paper and asked.


"You melon WA, always dismantle Lao Tai do what!" ...... Ah, little ho you don't worry, I'm going to explain how to find the suffix node, "said Little Hi, smiling."

Tip three: How to solve the suffix node of each node in the trie tree

I see So I know the suffix node of each node, and then I can easily solve the problem that Mr. Crab gave me! Little Ho said happily, "but where is the trie map?" ”

Little hi not by laughing: "You call this maiduhuanzhu you know?" Remember that when we compute the suffix node, we calculate from each point, through each char (e.g. ' a '. d ') will come to the junction? Add these sides to the trie tree, which is the trie map! ”

"That's the way it is, but these edges feel useless in addition to counting the suffix nodes." Little Ho started asking questions again.

"This is the trie of the map, you think about when you need to know the suffix node of a node?" "Little hi really can't bear to see his brother so cute, can only resist the interpretation of the temperament."

Small Ho suddenly dawned, " in this node can not continue and the article Str continue to match the time, that is, this node does not" the next character of the article "corresponding to that side, oh! I know, in the trie diagram, each node is full of all the edges, so the original need to find the suffix node and then "str next character" Such an edge to find the next node, now can be directly through the current node "str next character" Such an edge can then be matched down, If there is this side, it does not need to say, and if this side is based on the suffix knot completion, that is the result we want! "

"So then!" The way to accomplish this is generally the case, based on the dictionary to build a trie tree, and then according to what we said before the corresponding trie map, and then from the root node of the trie graph, along the article str each character, out of the corresponding edge, Until a marker node is encountered or the entire STR has been matched to complete ~ "small hi timely summing up the way."

"And this time complexity is at O (nl+m) level!" I think it is enough to complete the requirements of Mr. Crab ~ "Little Ho moved his finger," said.

Yes But what Mr. Crab asked for is not an idea, but he wanted us to write the program to it! ”

Input

Each input file has and has only one set of test data.

The first behavior of each test data is an integer n, which indicates the size of the crab dictionary.

The next n rows, each of which acts a river crab word consisting of lowercase English letters.

The next line is an article with a length of not more than M, made up of lowercase English letters.

For 60% of the data, the total length of all the words of the river crab is less than ten, m<=10

For 80% of the data, the total length of all river crab words is less than 10^3, m<=10^3

For 100% of the data, the total length of all river crab words is less than 10^6, M<=10^6, n<=1000

Output

For each set of test data, the output line "YES" or "NO" indicates whether the article contains river crab words.

Sample input
6aaabcaaacabccacbcdcdaaaaaaaaaaabaaadaaac
Sample output
YES


Parse: trie diagram template. AC automata belong to a structure of trie diagram.


Trie Figure details see: Trie (DFA), AC automata




AC Code:

#include <cstdio> #include <cstring> #include <queue>using namespace std;const int max_sigma = 26;class    node{public:node* fail;    node* Next[max_sigma];    int cnt;        Node () {memset (next, 0, sizeof (next));        Fail = NULL;    CNT = 0;    }};class ac_automato:public Node{public:node *root;    int head, tail;        void Clear () {root = new Node ();    Head = tail = 0;        } void Insert (char* s) {int C;        node* p = root;            while (*s! = NULL) {c = *s-' a ';            if (p->next[c] = = NULL) P->next[c] = new Node ();            p = p->next[c];        s + +;    } p->cnt + +;        } void Build () {root->fail = NULL;        queue<node* > Q;        Q.push (root);            while (!q.empty ()) {node* tmp = Q.front ();            node* p = NULL;            Q.pop (); for (int i=0; i<max_sigma; i++) {if (Tmp->next[i]! = NULL) {if (tMP = = root) Tmp->next[i]->fail = root;                        else{p = tmp->fail; while (P! = null) {if (p->next[i]! = null) {Tmp->next[i]-&gt                                ; fail = p->next[i];                            Break                        } p = p->fail;                    } if (p = = NULL) Tmp->next[i]->fail = root;                } q.push (Tmp->next[i]);        }}}} int find (char* s) {int cnt = 0, C;        node* p = root;            while (*s! = NULL) {c = *s-' a ';            while (p->next[c] = = NULL && p! = root) p = p->fail;            p = p->next[c];            if (p = = NULL) p = root;            node* tmp = p;           while (tmp! = root && tmp->cnt! =-1) {cnt + = tmp->cnt;     tmp->cnt =-1;            TMP = tmp->fail;        } s + +;    } return CNT;    }} Ac;char word[1000002], text[1000002]; Word is small, it will re!!!.    int main () {#ifdef sxk freopen ("In.txt", "R", stdin);    #endif//SXK int n;        while (scanf ("%d", &n) = = 1) {ac.clear ();            for (int i=0; i<n; i++) {scanf ("%s", word);        Ac.insert (word);        } ac.build ();        scanf ("%s", text); Puts (Ac.find (text)?    "YES": "NO"); } return 0;}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Hihocoder #1036: trie diagram (AC automaton)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.