-
Notifications
You must be signed in to change notification settings - Fork 0
/
dict_opt.cpp
122 lines (98 loc) · 1.77 KB
/
dict_opt.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include <iostream>
#include <vector>
#include <string>
#include <cstdio>
using namespace std;
string alpha = "abcdefghijklmnopqrstuvwxyz";
struct node {
bool presence;
node* v[26];
node () {
for ( int i = 0; i < 26; i++ ) {
v[i] = NULL;
}
presence = false;
}
};
class trie {
node* head;
public :
void insert(string &s ) {
node* tmp = head;
for ( int i = 0; i < s.size(); i++ ) {
if ( tmp->v[s[i] - 97] == NULL ) {
tmp->v[s[i] - 97] = new node;
}
if ( i == s.size() - 1) {
tmp->v[s[i] - 97]->presence = true;
break;
}
tmp = tmp->v[s[i] - 97];
}
}
node* search(string &s) {
node* tmp = head;
for ( int i = 0; i < s.size(); i++ ) {
int index = s[i] - 97;
if ( tmp->v[index] == NULL ) {
return NULL;
} if ( i == s.size() - 1) {
return (tmp->v[index]);
}
tmp = tmp->v[index];
}
}
void print_all( node* head, string &s ) {
if ( head == NULL ) {
return;
}
if ( head->presence ) {
printf("%s\n", s.c_str());
}
for ( int i = 0; i < 26; i++ ) {
if ( head->v[i] != NULL ) {
s += alpha[i];
print_all(head->v[i], s);
s.erase(s.end() - 1);
}
}
}
trie() {
head = new node;
}
};
int main()
{
trie t;
int n;
scanf("%d", &n);
for ( int i = 0; i < n; i++ ) {
string s;
cin >> s;
// scanf("%s", s);
t.insert(s);
}
int k;
// cin >> k;
scanf("%d", &k);
for ( int i = 0; i < k; i++ ) {
string s;
// char s[21];
// scanf("%s", &s);
cin >> s;
cout << "Case #" << i + 1 << ":" << endl;
node* srch = t.search(s);
if ( srch != NULL ) {
if ( srch->presence ) {
srch->presence = false;
t.print_all(srch, s);
srch->presence = true;
} else {
t.print_all(srch, s);
}
} else {
cout << "No match." << endl;
}
}
return 0;
}