From 5f080c190353afe76cb60cea9ae5084f4bff35bb Mon Sep 17 00:00:00 2001 From: Eric Mertens Date: Thu, 10 Nov 2022 11:28:03 -0800 Subject: [PATCH] 18 --- 2019/18.cpp | 31 +++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/2019/18.cpp b/2019/18.cpp index 7274495..14db007 100644 --- a/2019/18.cpp +++ b/2019/18.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include @@ -110,19 +111,33 @@ auto SetKey(Doors doors, char key) { return doors.set(std::toupper(key) - 'A'); } -auto SolveMaze(Distances const& distances, std::set const initial_locations) -> std::int64_t { +template +auto MakePQueue(Compare const& compare) + -> std::priority_queue, Compare> +{ + return {compare}; +} + +auto SolveMaze( + Distances const& distances, + std::set const initial_locations +) -> std::int64_t +{ // Track current positions and current set of keys in easy to compare form using Visited = std::pair, unsigned long long>; std::set seen; - std::multimap, Doors>> todo - {{0, {initial_locations, Doors()}}}; + auto todo = MakePQueue, Doors>>( + [](auto const& x, auto const& y) { + return std::get<0>(x) > std::get<0>(y); + } + ); + + todo.emplace(0, initial_locations, Doors()); while (!todo.empty()) { - auto it = todo.begin(); - auto [steps, ld] = *it; - auto& [locations,keys] = ld; - todo.erase(it); + auto [steps, locations, keys] = todo.top(); + todo.pop(); if (keys.all()) { return steps; } @@ -134,7 +149,7 @@ auto SolveMaze(Distances const& distances, std::set const initial_location auto [cost, need] = costneed; if ((need & ~keys).none()) { auto locations2 = locations1; locations2.insert(next); - todo.insert({steps + cost, {locations2, SetKey(keys, next)}}); + todo.emplace(steps + cost, locations2, SetKey(keys, next)); } } }