-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathTrie.cpp
More file actions
139 lines (101 loc) · 2.11 KB
/
Trie.cpp
File metadata and controls
139 lines (101 loc) · 2.11 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
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
#include <iostream>
#include<bits/stdc++.h>
#define ll long long int
#define lld long double
#define F first
#define S second
#define f(i,a,b) for(int i=a;i<=b;i++)
#define g(i,a,b) for(int i=a;i>=b;i--)
#define pb push_back
#define mh make_heap
#define ph push_heap
#define pq priority_queue
#define bits(x) __builtin_popcountll(x)
#define op(x) cout<<"Case #"<<x<<": "
#define op1(x) cout<<"Scenario #"<<x<<": "
#define endl "\n"
using namespace std;
const ll mod = 1000000007;
const ll INF = LLONG_MAX;
const ll NEGINF = LLONG_MIN;
const int N = 18;
const ll MAXN = 1000001;
struct trie
{
struct trie *children[26];
bool isEndOfWord;
ll count = 0;
};
struct trie *getNode(void)
{
struct trie *pNode = new trie;
pNode->isEndOfWord = false;
pNode->count = 0;
for (int i = 0; i < 26; i++)
pNode->children[i] = NULL;
return pNode;
}
void insert(struct trie *root, string & key)
{
struct trie *pCrawl = root;
for (int i = 0; i < key.length(); i++)
{
int index = key[i] - 'a';
if (pCrawl->children[index] == NULL)
pCrawl->children[index] = getNode();
pCrawl = pCrawl->children[index];
}
pCrawl->isEndOfWord = true;
pCrawl->count++;
}
bool search(struct trie *root, string key)
{
struct trie *pCrawl = root;
for (int i = 0; i < key.length(); i++)
{
int index = key[i] - 'a';
if (!pCrawl->children[index])
return false;
pCrawl = pCrawl->children[index];
}
return (pCrawl != NULL and pCrawl->isEndOfWord);
}
void dfs(struct trie *node)
{
for (int i = 0; i < 26; i++)
{
if (node->children[i] != NULL)
{
dfs(node->children[i]);
}
}
}
void solve(int t)
{
ll n;
cin >> n;
string s;
trie *root = getNode();
for (int i = 0; i < n; i++)
{
cin >> s;
insert(root, s);
}
dfs(root);
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int t = 1;
cin >> t;
for (int i = 1; i <= t; i++)
{
solve(i);
}
}