-
Notifications
You must be signed in to change notification settings - Fork 0
/
TRIE_new.cpp
63 lines (46 loc) · 1.02 KB
/
TRIE_new.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
#include<bits/stdc++.h>
using namespace std;
bool pre;
struct TRIE {
bool endmark;
TRIE *next[10];
TRIE() {
endmark=false;
for(int i=0; i<=9; i++) next[i]=NULL;
}
} *root;
void insert_(string str, TRIE *curr) {
int cnt = 0;
int len = str.size();
for(int i=0; i<len; i++) {
int id = str[i] - '0';
if(curr->next[id]==NULL) {
curr->next[id] = new TRIE();
} else cnt++;
if(curr->endmark) pre = true;
curr = curr->next[id];
}
if(cnt==len) pre = true;
curr->endmark = true;
}
void delete_(TRIE *root) {
for(int i=0; i<=9; i++) {
if(root->next[i]) {
delete_(root->next[i]);
}
}
delete root;
}
int main() {
root = new TRIE();
pre = false; // determines suffix presence
string s;
int queries;
cin>>queries;
for(int i=1; i<=queries; i++) {
cin>>s;
insert_(s, root);
}
delete_(root); // clear memory, else will result in MLE
return 0;
}