-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrie树
99 lines (90 loc) · 1.65 KB
/
Trie树
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
#define SIZE 26
typedef struct TrieNode
{
int count;
struct TrieNode* next[SIZE];
}TrieNode;
TrieNode *pRoot;
TrieNode* createTrieNode()
{
TrieNode *p=NULL;
p=(TrieNode *)malloc(sizeof(TrieNode));
if(!p)
exit(1);
p->count=0;
memset(p->next,0,sizeof(TrieNode*)*SIZE);
return p;
}
void initialTrie()
{
pRoot=createTrieNode();
return;
}
void insertTrieNode(TrieNode *pRoot,char *s)
{
TrieNode *p;
int tag;
p=pRoot;
assert(s!=NULL);
while(*s)
{
tag=*s-'a';
if((p->next[tag])==NULL)
{
p->next[tag]=createTrieNode();
}
(p->count)++;
p=p->next[tag];
s++;
}
(p->count)++;
}
int searchTrieNode(TrieNode *pRoot,char *s)
{
TrieNode *p;
p=pRoot;
int t=0,tag;
while(*s)
{
tag=*s-'a';
if(p->next[tag]!=NULL)
{
p=p->next[tag];
t=p->count;
}
else
{
return 0;
}
s++;
}
return t;
}
int main()
{
char a[50];
int i,n,m;
pRoot=NULL;
initialTrie();
while(scanf("%d",&n)!=EOF)
{
for(i=0;i<n;i++)
{
scanf("%s",a);
insertTrieNode(pRoot,a);
}
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%s",a);
m=searchTrieNode(pRoot,a);
printf("%d\n",m);
}
}
system("pause");
return 0;
}