[LeetCode] Minimum Number of People to Teach

1733. Minimum Number of People to Teach

On a social network consisting of m users and some friendships between users, two users can communicate with each other if they know a common language.

You are given an integer n, an array languages, and an array friendships where:

  • There are n languages numbered 1 through n,
  • languages[i] is the set of languages the i​​​​​​th​​​​ user knows, and
  • friendships[i] = [u​​​​​​i​​​, v​​​​​​i] denotes a friendship between the users u​​​​​​​​​​​i​​​​​ and vi.

You can choose one language and teach it to some users so that all friends can communicate with each other. Return the minimum number of users you need to teach.

Note that friendships are not transitive, meaning if x is a friend of y and y is a friend of z, this doesn’t guarantee that x is a friend of z.

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
41
42
class Solution {
unordered_map<int, unordered_set<int>> speak;
int adj[555][555] = {};
void connect(int u, int v) {
if(speak[u].size() > speak[v].size()) swap(u,v);
for(auto& s : speak[u]) {
if(speak[v].count(s)) {
adj[u][v] = adj[v][u] = true;
break;
}
}
}
public:
int minimumTeachings(int n, vector<vector<int>>& languages, vector<vector<int>>& friendships) {
for(int i = 0; i < languages.size(); i++) {
speak[i+1] = unordered_set<int>(begin(languages[i]), end(languages[i]));
}
for(auto& f : friendships) {
int u = f[0], v = f[1];
connect(u, v);
}
int res = INT_MAX;
for(int lang = 1; lang <= n; lang++) {
int now = 0;
vector<int> learn(languages.size() + 1);
for(auto& f : friendships) {
int u = f[0], v = f[1];
if(adj[u][v]) continue;
if(!speak[u].count(lang) and !learn[u]) {
learn[u] = true;
now++;
}
if(!speak[v].count(lang) and !learn[v]) {
learn[v] = true;
now++;
}
}
res = min(res,now);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/16/PS/LeetCode/minimum-number-of-people-to-teach/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.