about summary refs log tree commit diff stats
path: root/src/network_set.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'src/network_set.cpp')
-rw-r--r--src/network_set.cpp68
1 files changed, 68 insertions, 0 deletions
diff --git a/src/network_set.cpp b/src/network_set.cpp new file mode 100644 index 0000000..3238dcd --- /dev/null +++ b/src/network_set.cpp
@@ -0,0 +1,68 @@
1#include "network_set.h"
2
3void NetworkSet::Clear() {
4 networks_.clear();
5 network_by_item_.clear();
6}
7
8int NetworkSet::AddLink(int id1, int id2) {
9 if (id2 > id1) {
10 // Make sure id1 < id2
11 std::swap(id1, id2);
12 }
13
14 if (network_by_item_.count(id1)) {
15 if (network_by_item_.count(id2)) {
16 int network_id1 = network_by_item_[id1];
17 int network_id2 = network_by_item_[id2];
18
19 networks_[network_id1].emplace(id1, id2);
20
21 if (network_id1 != network_id2) {
22 for (const auto& [other_id1, other_id2] : networks_[network_id2]) {
23 network_by_item_[other_id1] = network_id1;
24 network_by_item_[other_id2] = network_id1;
25 }
26
27 networks_[network_id1].merge(networks_[network_id2]);
28 networks_[network_id2].clear();
29 }
30
31 return network_id1;
32 } else {
33 int network_id = network_by_item_[id1];
34 network_by_item_[id2] = network_id;
35 networks_[network_id].emplace(id1, id2);
36
37 return network_id;
38 }
39 } else {
40 if (network_by_item_.count(id2)) {
41 int network_id = network_by_item_[id2];
42 network_by_item_[id1] = network_id;
43 networks_[network_id].emplace(id1, id2);
44
45 return network_id;
46 } else {
47 int network_id = networks_.size();
48 network_by_item_[id1] = network_id;
49 network_by_item_[id2] = network_id;
50 networks_.emplace_back();
51 networks_[network_id] = {{id1, id2}};
52
53 return network_id;
54 }
55 }
56}
57
58bool NetworkSet::IsItemInNetwork(int id) const {
59 return network_by_item_.count(id);
60}
61
62int NetworkSet::GetNetworkWithItem(int id) const {
63 return network_by_item_.at(id);
64}
65
66const std::set<std::pair<int, int>>& NetworkSet::GetNetworkGraph(int id) const {
67 return networks_.at(id);
68}