Link:
Http://acm.hdu.edu.cn/showproblem.php? PID = 1, 1251
Question
Problem descriptionignatius recently encountered a problem. The teacher gave him many words (only lowercase letters are used and no duplicate words will appear ), the teacher asks him to calculate the number of words prefixed with a certain string (the word itself is also its own prefix ).
The first part of input data is a word table. Each line has one word. The length of a word cannot exceed 10. These words represent words that the teacher gave to Ignatius for statistics. A blank line indicates the end of the word table. the second part is a series of questions. Each question in each row is a string.
Note: This question only contains a set of test data, which is processed until the end of the file.
Output provides the number of words prefixed with this string for each question.
Sample Input
bananabandbeeabsoluteacmbabbandabc
Sample output
2310
Analysis and Summary:
One of the basic functions of the dictionary tree is to calculate the number of prefixes.
Code:
# Include <iostream> # include <cstdio> # include <cstring> using namespace STD; const int kind = 26; const int maxn = 150000; int cntnode; struct node {bool isword; int prefix; node * Next [kind]; void Init () {isword = 0; prefix = 0; memset (next, 0, sizeof (next ));}} heap [maxn]; inline node * newnode () {heap [cntnode]. init (); Return & heap [cntnode ++];} void insert (node * root, char * Str) {for (char * P = STR; * P; + p) {int CH = * P-'A'; If (root-> next [CH] = NULL) {root-> next [CH] = newnode ();} root = root-> next [CH]; root-> prefix ++;} root-> isword = true ;} int count (node * root, char * Str) {// number of returned prefixes int sum = 0; For (char * P = STR; * P; ++ P) {char CH = * P-'A'; If (root-> next [CH] = NULL) return 0; root = root-> next [CH];} return root-> prefix;} int main () {char STR [12]; node * root = newnode (); While (gets (STR )) {If (STR [0] = 0) break; insert (root, STR) ;}while (gets (STR) {printf ("% d \ n ", count (root, STR);} return 0 ;}
-- The significance of life is to give it a meaningful person.
Original Http://blog.csdn.net/shuangde800,
D_double (reprinted please mark)