Skip to content

Commit 95e3e90

Browse files
authored
Create minimum-number-of-people-to-teach.cpp
1 parent 403a32d commit 95e3e90

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Time: O(n * m^2)
2+
// Space: O(n * m)
3+
4+
class Solution {
5+
public:
6+
int minimumTeachings(int n, vector<vector<int>>& languages, vector<vector<int>>& friendships) {
7+
vector<unordered_set<int>> language_sets;
8+
for (const auto& language : languages) {
9+
language_sets.emplace_back(cbegin(language), cend(language));
10+
}
11+
unordered_set<int> candidates;
12+
for (const auto& f : friendships) {
13+
if (empty(intersect(language_sets[f[0] - 1], language_sets[f[1] - 1]))) {
14+
candidates.emplace(f[0] - 1);
15+
candidates.emplace(f[1] - 1);
16+
}
17+
}
18+
vector<int> count(n);
19+
for (const auto& i : candidates) {
20+
for (const auto& l : language_sets[i]) {
21+
++count[l - 1];
22+
}
23+
}
24+
return size(candidates) - *max_element(cbegin(count), cend(count));
25+
}
26+
27+
private:
28+
unordered_set<int> intersect(const unordered_set<int>& a, const unordered_set<int>& b) {
29+
if (size(a) > size(b)) {
30+
return intersect(b, a);
31+
}
32+
unordered_set<int> result;
33+
for (const auto& x : a) {
34+
if (b.count(x)) {
35+
result.emplace(x);
36+
}
37+
}
38+
return result;
39+
}
40+
};

0 commit comments

Comments
 (0)