Hihocoder #1014: Trie tree (number of dictionary occurrences of the tree statistic prefix * "template" based on pointer structure implementation)

Source: Internet
Author: User

#1014: Trie Tree Time limit:10000msSingle Point time limit:1000msMemory Limit:256MBDescribe

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 met a dictionary, so little hi to small ho raised the classic question: "Little ho, can you for each of the strings I gave, in this dictionary to find all the words starting with this string?" "

The battle-hardened Little Ho replied: "How can not it!" You give me a string, I go through all the words in the dictionary, check that you give me the string is not the prefix of this word is it? "

Little hi smiled: "You ah, still too young!" ~ Suppose there are 100,000 words in this dictionary, I ask you 10,000 times, which month do you have to count? ”

Small Ho bowed down a count, look at that pile of 0, immediately feel oneself this life will spend on above ...

Small hi look at small ho's embarrassing kind, also continue to smile: "Let me improve your knowledge level bar ~ Do you know the tree such a data structure?" ”

Small Ho thought, said: "Know ~ it is a basic data structure, as here said!" ”

Small hi satisfied nodded, said: "Then you know how I use a tree to represent the whole dictionary?" ”

Little Ho shook his head and said he was not clear.

Hint one: establishment of trie tree

"You see, we have now got such a tree, then you see, if I give you a string AP, how do you find all the words that start with the AP?" "Little hi again began to test Xiao Ho."

"Hmm ... Iterate through all the words? Little Ho still does not forget the algorithm that he first proposed.

Stupid This tree is built in white! "Little Hi, after the little Ho," continued the way: "Watch! ”

Tip Two: How to use the trie tree

Tip Three: In the establishment of trie tree at the same time statistics!

"Then now!" Go to the code to achieve it! "said Little hi.

xClose Hint one: establishment of trie tree

Small hi so on the paper for a while, handed to small ho, the way: "You see this tree and this dictionary have what relationship?" ”

Little Ho stared at the paper and thought for a minute: "I know!" for the path from the root node of the tree to each black node, if the letters on the path are connected, they all correspond to one word in the dictionary! "

Little Hi said: "Then do you know how to build such a tree from a dictionary?" ”

"Not Made!" ”

"Think you do not know, I come to tell you ~" Little Hi put on a teacher's appearance, said: "You think so, if I already have a dictionary and a corresponding tree, I want to add a new word apart, what should I do? ”

"Let me think ..." Little Ho began to wonder: "First I have to see where I can go, right?" For example, I walk from the number 1th node "a" This side can go to the number 2nd node, and then from the 2nd node Walk "p" this side can go to the 3rd node, and then ... There's no way to go! At this point I need to add a line from node 3rd and marked "P" to go down ... This is the end! Then I'll mark the last node that I arrived at as black. ”

Small hi said: "Really clever ~ then you might as well if it is a dictionary with 10W words, the length of each word is not more than 10, how big is this tree?" ”

Little Ho then took out his pen and said: "Assuming I have made the first three words into a tree, then I want to add a new word, the worst case is that the word and the previous three words do not have a common prefix, then the length of the new word if it is 5, I will add at least 5 nodes to the tree in order to continue to represent this dictionary! ”

"And if every time is the worst case, the tree will have a maximum of 100W knots!" Not to mention the worst-case scenario is unlikely to happen a second time! After all, the alphabet is only 26 letters! "said Little Ho, continuing.

"Hmm ~ so we can use (the number of words * word length) a node to represent a dictionary?" Little Hi asked.

"Yes!" "Little ho Way:" But what's the use of such a tree? ”

"Do not underestimate it, it is the legendary trie tree Oh ~ As to what he has to use, a while you will know!" "Little hi smiled and answered."

Close xClose Tip Two: How to use the trie tree

Small hi in the tree with green marked a node, handed to small ho.

"This knot ... is to go from the root node first "a" and then go "p" to reach the node it! Oh, I know, all the markers in the subtree with this node root are words prefixed with "AP"! And all words prefixed with "AP" are in a subtree rooted in this node ~ "Little ho surprises."

"Yes, and you have an idea of how to solve my problem?" "Little Hi Chase asked."

"Hmm ... That is, every time I get your string, I find the corresponding node in the tree, and then count how many of the nodes are there? "Little Ho is not very sure to answer:" But this ... It seems that in the worst case, when you give a string a short time, I still have to scan a large part of this tree? This means that while the average time complexity is reduced, the worst-case time complexity is still high! ”

Small hi smiled: "I did not expect you to see out of it ~ I thought it would teach you again!" ~ Well, do you have any good solutions? ”

"Not yet!" Little hi You don't suspense, tell me now! The tortured little Ho began to beg for mercy.

"All right!" I will help you this time ~ "

Close xClose Tip Three: In the establishment of trie tree at the same time statistics!

"Little Ho Have you ever thought of such a question?" It may be said that the number of nodes in the subtree of the root of T is l[t], since I want to count a l[t1], and this node is uncertain, I have no way to all the nodes of the l[t] to find out? "Little hi tidied up the thoughts, asked."

"There seems to be some," the teacher said before, "What is recursion?" Little Ho replied.

"Recursion is too complicated!" We can say later, you think, when you build the trie tree, when you go through a node, what does it say? "Little Hi left the head," continued the ask.

"I think, after a knot ... Tag node ... It shows that the subtree with this node as the root will have more than one marker node? ”

Yes Do you have any way to record this change? ”

"I think I'm going to start with all the l[t]=0, and then every time I add a new word, all the nodes that pass through the l[t] are all +1, so I can count all the l[t at the same time when I'm finished building this trie tree , right? "Little Ho Happy Road."

Close Input

The first behavior of the input is a positive integer n, which indicates the size of the dictionary, followed by n lines, one word per line (not guaranteed to be an English word, or possibly a Martian word), a word consisting of no more than 10 lowercase English letters, possibly with the same word, which should be treated as a different word. The next behavior is a positive integer m, which indicates the number of times the small hi inquired, followed by the M-line, each line a string consisting of a lowercase English letter of not more than 10, which represents a query for small hi.

In 20% of the data is N, m<=10, the dictionary size <=2.

In 60% of the data is N, m<=1000, the dictionary size <=5.

In 100% of the data is N, m<=100000, the dictionary size <=26.

The subject by the amount of data to be ranked Oh ~

Output

For each query of little hi, output an integer ans, which represents the number of words prefixed by the string in the dictionary given by small hi.

Sample input
5babaabbabbbaaaaabbaaaaaabaababaababb5babbbaabaaababbbbbabbaab
Sample output
10300


Algorithmic analysis: The standard Trie algorithm trains the topic, because the search () function returns an error that determines the condition, resulting in a long time debug!

Almost affected their confidence in the use of the pointer, when the training is not willing to listen to the teacher, in a lot of words to write the algorithm application of the pointer implementation. At least
For the use of one-level pointers is still possible!
In the afternoon, we analyzed the trie array implementation algorithm in the Rujia Training guide for a long time. Not very understand, waiting to continue! Finally, I decided to write the pointer.
Code:
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <algorithm>using namespace std;struct node{int flag;//used to store paths through this node (word) struct node *next[26];};    struct node *newnode ()//This is the beginning of the root node of the entire dictionary tree to be created {int i;    struct node *p;    p=new struct node;    for (i=0; i<26; i++) {p->next[i] = NULL; } p->flag=0; This is used to mark the return p;};    void Insert (struct node *root, char *s) {struct node *p=root;//must be replaced here to ensure that the P pointer in the main function is the head pointer invariant int Len, I;    int t;    Len=strlen (s);    struct node *temp;        for (i=0; i<len; i++) {t=s[i]-' a ';            if (p->next[t]==null) {temp=newnode ();            temp->flag++;            printf ("%d--", Temp->flag);            p->next[t]=temp;        p=p->next[t];            } else {p=p->next[t];           p->flag++;        printf ("%d**", P->flag); }}//printf ("\ n");} int Search (struct node *root, chaR *t) {int i, TT;    int Len=strlen (t);    struct node *p=root;    int cnt;        for (i=0; i<len; i++) {tt=t[i]-' a ';            if (p->next[tt]!=null) {p=p->next[tt];            cnt=p->flag;        printf ("%d--%d**", P->flag, CNT);    } else break;    } if (I==len) return CNT; else return 0;}    struct node *p;int main () {int n, m;    scanf ("%d", &n);    int I, J;    Char s[20], t[20];    P=newnode ();        for (i=0; i<n; i++) {scanf ("%s", s);    Insert (P, s);    } scanf ("%d", &m);        for (i=0; i<m; i++) {scanf ("%s", T);        int k = Search (P, t);    printf ("%d\n", K); } return 0;}

Hihocoder #1014: Trie tree (number of dictionary occurrences of the tree statistic prefix * "template" based on pointer structure implementation)

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.