-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDict.cpp
145 lines (118 loc) · 2.27 KB
/
Dict.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#include <iostream>
#include <vector>
#include <string>
#include <cstdio>
using namespace std;
string alpha = "abcdefghijklmnopqrstuvwxyz";
struct node {
bool presence;
vector<node* > v;
node () {
for ( int i = 0; i < 26; i++ ) {
v.push_back(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_similar( node* head, string &s ) {
if ( head == NULL )
return;
if ( head->presence ) {
cout << s << endl;
string s2 = s;
for ( int i = 0; i < (head->v).size(); i++ ) {
if ( head->v[i] != NULL ) {
s2 += alpha[i];
print_all_similar(head->v[i], s2 );
s2[s2.size() - 1] = '\0';
}
}
return;
}
string s2 = s;
for ( int i = 0; i < (head->v).size(); i++ ) {
if ( head->v[i] != NULL ) {
s2 += alpha[i];
print_all_similar(head->v[i], s2 );
s2.erase(s2.end() - 1);
}
}
}
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 < (head->v).size(); 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;
t.insert(s);
}
int k;
scanf("%d", &k);
for ( int i = 0; i < k; i++ ) {
string 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;
}