-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrie.cpp
More file actions
81 lines (71 loc) · 1.39 KB
/
trie.cpp
File metadata and controls
81 lines (71 loc) · 1.39 KB
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
#include <bits/stdc++.h>
using namespace std;
const int C = 85;
const int LETRAS = 30;
struct No{
No *filho[LETRAS];
int prefix_cont; // numero de prefixos comuns das strings da raiz ate o no.
bool folha;
};
No * init(){
No *novo = (No *)malloc(sizeof(No));
novo->prefix_cont = 0;
novo->folha = false;
for(int i = 0; i < 26; i++){
novo->filho[i] = NULL;
}
return novo;
}
No * constroi_trie(No *raiz, char str[]){
No *atual = raiz;
int sz = strlen(str);
for(int i = 0; i < sz; i++){
int ch = str[i] - 'a';
if(atual->filho[ch] == NULL){
atual->filho[ch] = init();
}
atual->filho[ch]->prefix_cont++;
atual = atual->filho[ch];
}
atual->folha = true;
return raiz;
}
bool busca(No *atual, char str[]){
int sz = strlen(str);
for(int i = 0; i < sz; i++){
int ch = str[i] - 'a';
if(atual->filho[ch] == NULL){
return false;
}
atual = atual->filho[ch];
}
return atual->folha;
}
void destroi_trie(No *atual){
for(int i = 0; i < 26; i++){
if(atual->filho[i] != NULL){
destroi_trie(atual->filho[i]);
}
}
free(atual);
atual = NULL;
}
int main(){
int n;
char str[C];
No *raiz = NULL;
raiz = init();
scanf("%d", &n);
while(n--){
scanf(" %s", str);
raiz = constroi_trie(raiz, str);
}
scanf("%d", &n);
while(n--){
scanf(" %s", str);
bool ret = busca(raiz, str);
printf("%s\n", ret ? "Achou" : "Nao achou");
}
destroi_trie(raiz);
return 0;
}