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; + }