Replace BFS with an ancestor search.

This commit is contained in:
2019-12-06 18:11:03 +01:00
parent 43e03c742b
commit 5c9dc0b6bd

View File

@@ -51,29 +51,23 @@ void aoc2019::day06_part1(std::istream &input, std::ostream &output) {
} }
void aoc2019::day06_part2(std::istream &input, std::ostream &output) { void aoc2019::day06_part2(std::istream &input, std::ostream &output) {
std::unordered_map<std::string, std::vector<std::string>> orbits; std::unordered_map<std::string, std::string> ancestors;
for (auto[a, b] : read_orbits(input)) { for (auto[a, b] : read_orbits(input)) {
orbits[a].emplace_back(b); ancestors[std::move(b)] = std::move(a);
orbits[b].emplace_back(a);
} }
std::deque<std::pair<std::string, int>> todo = {{"YOU", 0}}; std::unordered_map<std::string, int> santa_ancestors;
std::unordered_set<std::string> visited = { "YOU" };
while (!todo.empty()) { for (auto current = ancestors["SAN"]; current != "COM"; current = ancestors[current]) {
auto[name, offset] = todo.front(); santa_ancestors[ancestors[current]] = santa_ancestors[current] + 1;
todo.pop_front(); }
for (const auto& partner : orbits[name]) { int dist = 0;
if (partner == "SAN") { for (auto current = ancestors["YOU"]; current != "COM"; current = ancestors[current], ++dist) {
output << offset - 1 << std::endl; if (auto it = santa_ancestors.find(current); it != santa_ancestors.end()) {
return; output << dist + it->second << std::endl;
} return;
if (!visited.count(partner)) {
todo.emplace_back(partner, offset + 1);
visited.emplace(partner);
}
} }
} }