cpp: try ‹2092. Find All People With Secret›

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2024-02-24 23:24:11 +01:00
parent 231b55ed58
commit 2cd90d0db7
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,97 @@
#include <algorithm>
#include <iterator>
#include <set>
#include <vector>
class Solution {
void handle_previous_meeting(std::set<int> &overall,
std::set<int> &current) {
std::vector<int> 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<int> findAllPeople(int n,
std::vector<std::vector<int>> meetings,
int firstPerson) {
std::sort(meetings.begin(), meetings.end(),
[](const auto &l, const auto &r) { return l[2] < r[2]; });
std::set<int> knowers{0, firstPerson};
std::set<int> 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<int>(knowers.begin(), knowers.end());
}
};
#ifdef _MF_TEST
#include <gtest/gtest.h>
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