Link:
http://acm.hdu.edu.cn/showproblem.php?pid=1251
Topic
Problem Description
Ignatius recently encountered a problem, the teacher gave him a lot of words (only lowercase letters, no repetition of the words appear), now the teacher asked him to count the number of words prefixed with a string (the word itself is also a prefix).
Input
The first part of the input data is a list of words, each line a word, the length of the word is not more than 10, they represent the teacher to Ignatius statistics of the word, a blank line represents the end of the Word table. The second part is a series of questions, each line a question, each question is a string.
Note: Only one set of test data is processed to the end of the file.
Output
For each question, give the number of words prefixed with the string.
Sample Input
Banana
Band
Bee
absolute
ACM
BA
b
band
ABC
Sample Output
2
3
1
0
Analysis and Summary:
One of the basic functions of the dictionary tree, to find 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) {//return prefix number 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; }
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/