-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdigital_dictionary_trie.cpp
86 lines (71 loc) · 1.66 KB
/
digital_dictionary_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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include<bits/stdc++.h>
using namespace std;
class Node {
public:
Node* next[26];
bool end;
Node() {
for(int i=0; i<26; i++)
next[i] = NULL;
end = false;
}
};
class Trie {
Node *root;
public:
Trie() {
root = new Node();
}
void insertIntoTrie(string &s) {
Node *it = root;
for(auto c: s) {
if(!it->next[c-'a'])
it->next[c-'a'] = new Node();
it = it->next[c-'a'];
}
it->end = true;
}
void find(string &s) {
Node *it = root;
for(auto c: s) {
if(!it->next[c-'a']) {
cout<<"No suggestions found"<<endl;
insertIntoTrie(s);
return;
}
it = it->next[c-'a'];
}
vector<string> res;
printall(it, s, res, "");
for(auto c: res)
cout<<s<<c<<endl;
}
void printall(Node* it, string &s, vector<string> &res, string cur) {
if(it == NULL)
return;
if(it->end)
res.push_back(cur);
for(int i=0; i<26; i++) {
if(it->next[i])
printall(it->next[i], s, res, cur + char('a'+i));
}
}
};
int main() {
Trie t;
int n;
cin>>n;
vector<string> a(n);
for(auto &s: a) {
cin>>s;
t.insertIntoTrie(s);
}
int query;
cin>>query;
while(query--) {
string s;
cin>>s;
t.find(s);
}
return 0;
}