-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrie.cpp
71 lines (67 loc) · 1.21 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<bits/stdc++.h>
using namespace std;
const int SIZE=26;
struct node{
bool end; // To check if it is end of word.
node *arr[SIZE];
int cnt;
};
node *getnode()
{
node *n= new node;
n->end=false;
n->cnt=0;
for(int i=0;i<SIZE;i++)
{
n->arr[i]=NULL;
}
return n;
}
void insert(node *root, string st) // returns number of words having st as a prefix
{
node *tmp= root;
for(int i=0;i<st.length();i++)
{
int index=st[i]-'a';
if(tmp->arr[index]==NULL)
tmp->arr[index]=getnode();
tmp=tmp->arr[index];
tmp->cnt=tmp->cnt+1;
}
tmp->end=true;
}
int search(node *root, string st)
{
node *tmp = root;
int ans=0;
for(int i=0;i<st.length();i++)
{
int index=st[i]-'a';
if(tmp->arr[index]==NULL)
{
ans=0;
break;
}
tmp=tmp->arr[index];
ans=tmp->cnt;
}
return ans;
}
int main()
{
int n,q;
cin>>n>>q;
string st;
node *root=getnode();
for(int i=0;i<n;i++)
{
cin>>st;
insert(root,st);
}
while(q--)
{
cin>>st;
cout<<search(root,st)<<endl;
}
return 0;
}