hdu-1521

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <cstring>
const int kMaxC = 26;
const int kMaxS = 11;
struct
{
int cnt;
Trie* next[kMaxC];
Trie(){
cnt = 0;
memset(next, 0, sizeof(next));
}
};
void BuildTrie(Trie *rt, const char *str)
{
int len = strlen(str);
for(int i = 0; i < len; ++i)
{
int loc = str[i] - 'a';
if(rt->next[loc] == NULL)
{
Trie *p = new Trie();
++p->cnt;
rt -> next[loc] = p;
rt = p;
}
else
{
rt = rt->next[loc];
++rt->cnt;
}
}
}
int QueryTrie(Trie *rt, char *str)
{
int ret = 0;
int len = strlen(str);
for(int i = 0; i < len; ++i)
{
if(rt->next[str[i] - 'a'] != NULL)
{
rt = rt->next[str[i] - 'a'];
ret = rt->cnt;
}
else
return 0;
}
return ret;
}
int main()
{
char str[kMaxS];
Trie *rt = new Trie();
while(gets(str))
{
if(strlen(str) == 0)break;
BuildTrie(rt, str);
}
while(gets(str))
{
printf("%dn", QueryTrie(rt, str));
}
return 0;
}