-
Notifications
You must be signed in to change notification settings - Fork 5
/
radix_tree.cpp
61 lines (54 loc) · 1.11 KB
/
radix_tree.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
// Radix tree
#include <bits/stdc++.h>
using namespace std;
struct node {
bool isWord;
node* next[26+1];
node() {
isWord = false;
for (int i = 0; i < 26; next[i] = NULL, i++);
}
} * root;
void insert(char* str, int len) {
node* cur = root;
for (int i = 0; i < len; i++) {
int id = str[i] - 'a';
if (cur->next[id] == NULL) cur->next[id] = new node();
cur = cur->next[id];
}
cur->isWord = true;
}
bool search(char* str, int len) {
node* cur = root;
for (int i = 0; i < len; i++) {
int id = str[i] - 'a';
if (cur->next[id] == NULL) return false;
cur = cur->next[id];
}
return cur->isWord;
}
void del(node* cur) {
for (int i = 0; i < 26; i++)
if (cur->next[i]) del(cur->next[i]);
delete(cur);
}
int main() {
int n, q;
root = new node();
puts("Enter number of words:");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
char s[50];
scanf("%s", s);
insert(s, strlen(s));
}
puts("Enter number of query:");
scanf("%d", &q);
for (int i = 0; i < q; i++) {
char s[50];
scanf("%s", s);
if (search(s, strlen(s))) puts("FOUND!");
else puts("NOT FOUND!");
}
return 0;
}