forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
minimum-number-of-people-to-teach.cpp
40 lines (38 loc) · 1.24 KB
/
minimum-number-of-people-to-teach.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Time: O(n * m^2)
// Space: O(n * m)
class Solution {
public:
int minimumTeachings(int n, vector<vector<int>>& languages, vector<vector<int>>& friendships) {
vector<unordered_set<int>> language_sets;
for (const auto& language : languages) {
language_sets.emplace_back(cbegin(language), cend(language));
}
unordered_set<int> candidates;
for (const auto& f : friendships) {
if (empty(intersect(language_sets[f[0] - 1], language_sets[f[1] - 1]))) {
candidates.emplace(f[0] - 1);
candidates.emplace(f[1] - 1);
}
}
vector<int> count(n);
for (const auto& i : candidates) {
for (const auto& l : language_sets[i]) {
++count[l - 1];
}
}
return size(candidates) - *max_element(cbegin(count), cend(count));
}
private:
unordered_set<int> intersect(const unordered_set<int>& a, const unordered_set<int>& b) {
if (size(a) > size(b)) {
return intersect(b, a);
}
unordered_set<int> result;
for (const auto& x : a) {
if (b.count(x)) {
result.emplace(x);
}
}
return result;
}
};