-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.cpp
More file actions
87 lines (69 loc) · 1.8 KB
/
solution.cpp
File metadata and controls
87 lines (69 loc) · 1.8 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
#include <vector>
#include <sstream>
#include <iostream>
#include <map>
using namespace std;
using OrbitMap = std::map<string, string>;
using DistanceMap = std::map<string, int>;
OrbitMap getInput() {
OrbitMap orbitMap;
string line;
while (getline(cin, line)) {
stringstream ss(line);
string parent, child;
getline(ss, parent, ')');
getline(ss, child, ')');
orbitMap.emplace(child, parent);
}
return orbitMap;
}
int orbitSum(OrbitMap orbitMap) {
int sum = 0;
for (const auto &mapping: orbitMap) {
string current = mapping.second;
sum++;
while (true) {
try {
current = orbitMap.at(current);
sum++;
} catch (const out_of_range &e) {
break;
}
}
}
return sum;
}
int orbitDistanceBetween(OrbitMap orbitMap, string a, string b) {
DistanceMap distanceMap{};
int distance = 0;
string current = orbitMap.at(a);
while (true) {
try {
distanceMap.emplace(current, distance++);
current = orbitMap.at(current);
} catch (const out_of_range &e) {
break;
}
}
distance = 0;
current = orbitMap.at(b);
while (true) {
try {
int match = distanceMap.at(current);
return match + distance;
} catch (const out_of_range &e) {
try {
current = orbitMap.at(current);
distance++;
} catch (const out_of_range &e) {
throw logic_error("No shared parent");
}
}
}
}
int main() {
OrbitMap orbitMap = getInput();
cout << orbitSum(orbitMap) << endl;
cout << orbitDistanceBetween(orbitMap, "YOU", "SAN") << endl;
return 0;
}