Merge branch 'main' of hub.v.glguy.net:glguy/aocpp

This commit is contained in:
Eric Mertens 2022-11-09 23:19:24 -08:00
commit ce5bf9ee19

View File

@ -45,27 +45,30 @@ auto Parse(std::istream & in) -> Recipes {
auto Topsort(Recipes const& recipes) -> std::vector<std::string>
{
// Kahn's algorithm
std::set<std::string> perm;
std::set<std::string> temp;
std::vector<std::string> result;
result.reserve(recipes.size());
auto visit_ = [&](auto& rec, std::string name) -> void {
if (!perm.contains(name)) {
if (!temp.insert(name).second) throw std::runtime_error{"cyclic recipes"};
if (recipes.contains(name)) {
for (auto && [_, c] : recipes.at(name).second) {
rec(rec, c);
std::map<std::string, bool> marks; // false temp, true done
auto const visit = [&](auto const& visit, auto const& name) -> void {
auto [mark_iterator, is_new] = marks.try_emplace(name, false);
auto& [_, is_done] = *mark_iterator;
if (is_new) {
auto const rit = recipes.find(name);
if (rit != recipes.end()) {
for (auto const& [_, c] : rit->second.second) {
visit(visit, c);
}
}
temp.erase(name);
perm.insert(name);
is_done = true;
result.push_back(name);
} else if (!is_done) {
throw std::runtime_error{"cyclic graph"};
}
};
auto visit = [&](auto name) { visit_(visit_, name); };
for (auto && [k,_] : recipes) {
visit(k);
for (auto const& [c,_] : recipes) {
visit(visit, c);
}
std::reverse(result.begin(), result.end());