# HDU1251 - Statistical puzzle [dictionary tree]

Ignatius recently encountered a problem. The teacher gave him many words (only lowercase letters, no repeated words). Now the teacher asked him to count the number of words prefixed with a string (the word itself is also its own prefix)

Input

The first part of the input data is a word list, one word in each line, the length of the word is no more than 10, they represent the words given by the teacher to Ignatius for statistics, and a blank line represents the end of the word list. The second part is a series of questions, one question in each line, and each question is a string

Note: there is only one set of test data in this question, which will be 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```

Idea: dictionary tree template topic, note that if you write with linked list simulation, you need to use C + + to submit, otherwise you will TLE, don't ask me why I know, because my head is iron.

```#include<stdio.h>
#include<string.h>
#include<iostream>
#include<stdlib.h>
using namespace std;
const int tn = 26;
struct node
{
int flag;
node *nxt[tn];
node()
{
for(int i = 0; i < tn; ++i)
nxt[i] = NULL;
flag = 0;
}
};
node *root;
void init()
{
root = new node();
}
void del(node *root)
{
for(int i = 0; i < tn; ++i)
if(root->nxt[i] != NULL)
del(root->nxt[i]);
delete root;
}
void ins(char *s)
{
int len = strlen(s);
node *now = root;
for(int i = 0; i < len; ++i)
{
int to = s[i] - 'a';
if(now->nxt[to] == NULL)
now->nxt[to] = new node();
now = now->nxt[to];
now->flag++;
}
}
int prefind(char *s)
{
int len = strlen(s);
node *now = root;
for(int i = 0; i < len; ++i)
{
int to = s[i] - 'a';
if(now->nxt[to] == NULL)
return 0;
now = now->nxt[to];
}
return now->flag;
}

int main()
{
init();
char str;
while(gets(str))
{
if(str=='\0')
break;
ins(str);
}
while(~scanf("%s",str))
{
printf("%d\n",prefind(str));
}
}```

Tags: Programming

Posted on Fri, 08 Nov 2019 11:41:40 -0500 by knnakai