-
Notifications
You must be signed in to change notification settings - Fork 0
/
trie.cpp
71 lines (66 loc) · 1.36 KB
/
trie.cpp
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
#include <iostream>
#include<string>
using namespace std;
#define N 26
struct trie
{
trie *children[N];
bool isleaf;
};
struct trie * Newnode()
{
trie * newnode = new trie;
for(int i = 0 ; i < N ; i++)
{
newnode -> children[i] = NULL;
}
newnode -> isleaf = false;
return newnode;
}
void insert_trie(string str,trie* root)
{
trie *current = root;
int n = str.size();
for( int i = 0 ; i < n ; i++)
{
if(!(current->children[str[i] - 'a']))
{
current -> children[str[i] - 'a'] = Newnode();
}
current = current -> children[str[i] - 'a'];
}
current -> isleaf = true;
}
int search_trie(string ptr, trie *root)
{
int n = ptr.size();
int i;
trie * current = root;
for(i = 0 ; i < n ; i++)
{
if(!(current -> children[ptr[i] - 'a'] ) )
return 0;
current = current -> children[ptr[i] - 'a'];
}
return current->isleaf;
}
int main() {
int t;
cin>>t;
trie * root = Newnode();
while(t--)
{
int n;
cin>>n;
for( int i = 0 ; i < n ; i++)
{
string str;
cin>>str;
insert_trie(str,root);
}
string search;
cin>>search;
cout<<search_trie(search,root)<<endl;
}
return 0;
}