From fb81c11ca940d7763d88ae956f6967f1a241fef9 Mon Sep 17 00:00:00 2001 From: Alexander Danilchenko <39950413+OlexanderD@users.noreply.github.com> Date: Wed, 30 Oct 2019 23:30:40 +0200 Subject: [PATCH] C++11 solution to the 8th chapter problem. (#145) * C++11 solution to 8th chapter problem. * Update 01_set_covering.cpp * Extra space correction --- .../c++11/01_set_covering.cpp | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 08_greedy_algorithms/c++11/01_set_covering.cpp diff --git a/08_greedy_algorithms/c++11/01_set_covering.cpp b/08_greedy_algorithms/c++11/01_set_covering.cpp new file mode 100644 index 0000000..b5b6125 --- /dev/null +++ b/08_greedy_algorithms/c++11/01_set_covering.cpp @@ -0,0 +1,59 @@ +#include +#include +#include + +std::unordered_set operator & (const std::unordered_set&, + const std::unordered_set&); +void operator -= (std::unordered_set&, + const std::unordered_set&); + +int main() { + std::unordered_set statesNeeded({ "mt", "wa", "or", "id", "nv", "ut", "ca", "az" }); + + std::unordered_map> stations; + stations.insert({ "kone", {"id", "nv", "ut"} }); + stations.insert({ "ktwo", {"wa", "id", "mt" } }); + stations.insert({ "kthree", {"or", "nv", "ca" } }); + stations.insert({ "kfour", {"nv", "ut" } }); + stations.insert({ "kfive", {"ca", "az" } }); + + std::unordered_set finalStations; + + while (!statesNeeded.empty()) { + std::string bestStation; + std::unordered_set statesCovered; + for (const auto& i : stations) { + std::unordered_set coverage = i.second & statesNeeded; + if (coverage.size() > statesCovered.size()) { + bestStation = i.first; + statesCovered = coverage; + } + } + statesNeeded -= statesCovered; + finalStations.insert(bestStation); + } + + for (const auto& i : finalStations) + std::cout << i << std::endl; + + system("pause"); + return 0; +} + + std::unordered_set operator & (const std::unordered_set& a, + const std::unordered_set& b) { + std::unordered_set result; + for (const auto& i : a) + for (const auto& j : b) + if (i == j) + result.insert(i); + return result; + } + +void operator -= (std::unordered_set& a, + const std::unordered_set& b) { + for (auto j = b.begin(); j != b.end(); ++j) + for (auto i = a.begin(); i != a.end(); ) + if (*i == *j) i = a.erase(i); + else ++i; + }