Statistical difficulties
Time Limit: 4000/2000 MS (Java/others) memory limit: 131070/65535 K (Java/Others)
Total submission (s): 13884 accepted submission (s): 5971 problem descriptionignatius recently encountered a problem where the teacher gave him many words (only lowercase letters, no repeated words ), 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
Idea: dictionary tree.
Code:
# Include <iostream> # include <cstdlib> # include <cstdio> # include <cstring> # define Max 26 using namespace STD; int n, m; char ss [1005]; struct trie // trie node declaration {int isstr; // records the number of words at the node after trie * Next [Max]; // son branch }; void insert (trie * root, const char * s) // insert the word s into the dictionary tree {If (root = NULL | * s = '\ 0 ') return; int I; trie * P = root; while (* s! = '\ 0') {If (p-> next [* s-'a'] = NULL) // if it does not exist, then create the node {trie * temp = (trie *) malloc (sizeof (trie); for (I = 0; I <Max; I ++) {temp-> next [I] = NULL;} temp-> isstr = 1; p-> next [* s-'a'] = temp; P = p-> next [* s-'a'];} else {P = p-> next [* s-'a']; p-> isstr ++;} s ++;} int search (trie * root, const char * s) {trie * P = root; while (P! = NULL & * s! = '\ 0') {P = p-> next [* s-'a']; s ++;} If (P! = NULL) return p-> isstr; return 0;} void del (trie * root) // release the heap space occupied by the entire dictionary tree {int I; for (I = 0; I <Max; I ++) {If (root-> next [I]! = NULL) {del (root-> next [I]) ;}} free (Root) ;}int main () {int I; trie * root = (trie *) malloc (sizeof (trie); for (I = 0; I <Max; I ++) {root-> next [I] = NULL ;} root-> isstr = 0; while (1) {gets (SS); If (strlen (SS) = 0 | ss [0] = '') break; insert (root, SS);} while (gets (SS )! = NULL) {printf ("% d \ n", search (root, SS);} del (Root); // It is important to release space. Return 0 ;} /* allocallalloalalall */