-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrie - Implemented with Array.cpp
More file actions
92 lines (74 loc) · 1.67 KB
/
Trie - Implemented with Array.cpp
File metadata and controls
92 lines (74 loc) · 1.67 KB
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
#include<bits/stdc++.h>
using namespace std;
#define MAX_NODE 100005
#define MAX_LEN 105
int node[MAX_NODE][52];
int isWord[MAX_NODE];
int root, node_no;
void init()
{
memset(isWord, 0, sizeof isWord);
root = 0;
node_no = 0;
for(int i = 0; i < 52; ++i)
node[root][i] = -1;
}
void insert(string str, int len)
{
int now = root, id;
for(int i = 0; i < len; ++i)
{
id = 0;
if(str[i] >= 'A' && str[i] <= 'Z')
id = str[i] - 'A';
else if(str[i] >= 'a' && str[i] <= 'z')
id = str[i] - 'a' + 26;
if(node[now][id] == -1)
{
node[now][id] = ++node_no;
for(int j = 0; j < 52; ++j)
node[node_no][j] = -1;
}
now = node[now][id];
}
++isWord[now];
}
int search(string str, int len)
{
int now = root, id;
for(int i = 0; i < len; ++i)
{
id = 0;
if(str[i] >= 'A' && str[i] <= 'Z')
id = str[i] - 'A';
else if(str[i] >= 'a' && str[i] <= 'z')
id = str[i] - 'a' + 26;
if(node[now][id] == -1)
return 0;
now = node[now][id];
}
return isWord[now];
}
int main()
{
int t, n, m;
string str;
cin >> t;
for(int tc = 1; tc <= t; ++tc)
{
init();
cin >> n;
while(n--)
{
cin >> str;
insert(str, str.size());
}
cin >> m;
while(m--)
{
cin >> str;
cout << search(str, str.size()) << endl;
}
}
return 0;
}