-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrie.cpp
More file actions
71 lines (58 loc) · 1.43 KB
/
Copy pathtrie.cpp
File metadata and controls
71 lines (58 loc) · 1.43 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
#include "trie.h"
/* Debug */
#include <iostream>
using std::cout;
using std::endl;
Trie::Trie()
: Nodes(1, Node())
{
}
inline Trie::Node* Trie::NewNode() {
Nodes.push_back(Node{});
return &Nodes.back();
}
inline Trie::Node* Trie::RootNode() {
return &Nodes.front();
}
inline const Trie::Node* Trie::RootNode() const {
return &Nodes.front();
}
void Trie::Add(const Key& record) {
auto* node = RootNode();
for (int level = 0; level < DEPTH; ++level) {
int edge = record[level];
{
std::lock_guard<std::mutex> nodes_add_lock(NodesAddMtx);
if (!node->Next.count(edge))
node->Next[edge] = NewNode();
}
node = node->Next[edge];
}
++(node->Counter);
}
Trie::Value Trie::Get(const Key& record) const {
auto* node = RootNode();
for (int level = 0; level < DEPTH; ++level) {
int edge = record[level];
node = node->Next.at(edge);
}
return node->Counter;
}
void Trie::Traverse(const Node* node, size_t level,
Key& key, OnRecordCallback OnRecord) const {
if (level == DEPTH) {
OnRecord(key, node->Counter);
return;
}
for (auto& p : node->Next) {
int edge = p.first;
auto* next_node = p.second;
key[level] = edge;
Traverse(next_node, level + 1, key, OnRecord);
}
}
void Trie::Traverse(OnRecordCallback OnRecord) const {
std::lock_guard<std::mutex> nodes_add_lock(NodesAddMtx);
Key key;
Traverse(RootNode(), 0u, key, OnRecord);
}