diff --git a/cpp/find-all-people-with-secret.cpp b/cpp/find-all-people-with-secret.cpp new file mode 100644 index 0000000..96721a7 --- /dev/null +++ b/cpp/find-all-people-with-secret.cpp @@ -0,0 +1,97 @@ +#include +#include +#include +#include + +class Solution { + void handle_previous_meeting(std::set &overall, + std::set ¤t) { + std::vector intersection; + std::set_intersection(current.begin(), current.end(), overall.begin(), + overall.end(), std::back_inserter(intersection)); + + if (!intersection.empty()) { + overall.insert(current.begin(), current.end()); + } + + current = {}; + } + + public: + std::vector findAllPeople(int n, + std::vector> meetings, + int firstPerson) { + std::sort(meetings.begin(), meetings.end(), + [](const auto &l, const auto &r) { return l[2] < r[2]; }); + + std::set knowers{0, firstPerson}; + + std::set current_meeting{}; + int timestamp = -1; + for (const auto &meeting : meetings) { + auto a = meeting[0]; + auto b = meeting[1]; + auto t = meeting[2]; + + if (t != timestamp) { + // handle the previous meeting + handle_previous_meeting(knowers, current_meeting); + timestamp = t; + } + + // just add the members and carry on + current_meeting.insert(a); + current_meeting.insert(b); + } + handle_previous_meeting(knowers, current_meeting); + + return std::vector(knowers.begin(), knowers.end()); + } +}; + +#ifdef _MF_TEST +#include + +TEST(examples, no_1) { + Solution s; + EXPECT_EQ( + (s.findAllPeople(6, + std::vector{std::vector{1, 2, 5}, std::vector{2, 3, 8}, + std::vector{1, 5, 10}}, + 1)), + (std::vector{0, 1, 2, 3, 5})); +} +TEST(examples, no_2) { + Solution s; + EXPECT_EQ( + (s.findAllPeople(4, + std::vector{std::vector{3, 1, 3}, std::vector{1, 2, 2}, + std::vector{0, 3, 3}}, + 3)), + (std::vector{0, 1, 3})); +} +TEST(examples, no_3) { + Solution s; + EXPECT_EQ( + (s.findAllPeople(5, + std::vector{std::vector{3, 4, 2}, std::vector{1, 2, 1}, + std::vector{2, 3, 1}}, + 1)), + (std::vector{0, 1, 2, 3, 4})); +} + +TEST(wrong_answer, no_1) { + Solution s; + EXPECT_EQ( + (s.findAllPeople(6, + std::vector{std::vector{0, 2, 1}, std::vector{1, 3, 1}, + std::vector{4, 5, 1}}, + 1)), + (std::vector{0, 1, 2, 3})); +} + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} +#endif