1733. Minimum Number of People to Teach #2156
-
Topics: On a social network consisting of You are given an integer
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. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine the minimum number of users to teach a single language such that every pair of friends can communicate through a common language. The solution involves checking each language as a candidate and calculating how many users need to learn it to satisfy all friendships that currently lack a common language. Approach
Let's implement this solution in PHP: 1733. Minimum Number of People to Teach <?php
/**
* @param Integer $n
* @param Integer[][] $languages
* @param Integer[][] $friendships
* @return Integer
*/
function minimumTeachings($n, $languages, $friendships) {
$m = count($languages);
$knows = array_fill(1, $m, array_fill(1, $n, false));
for ($i = 1; $i <= $m; $i++) {
foreach ($languages[$i - 1] as $lang) {
if ($lang >= 1 && $lang <= $n) {
$knows[$i][$lang] = true;
}
}
}
$unsatisfiedUsers = [];
foreach ($friendships as $friendship) {
$u = $friendship[0];
$v = $friendship[1];
$hasCommon = false;
for ($l = 1; $l <= $n; $l++) {
if ($knows[$u][$l] && $knows[$v][$l]) {
$hasCommon = true;
break;
}
}
if (!$hasCommon) {
$unsatisfiedUsers[$u] = true;
$unsatisfiedUsers[$v] = true;
}
}
if (empty($unsatisfiedUsers)) {
return 0;
}
$minTeach = PHP_INT_MAX;
for ($l = 1; $l <= $n; $l++) {
$count = 0;
foreach (array_keys($unsatisfiedUsers) as $user) {
if (!$knows[$user][$l]) {
$count++;
}
}
if ($count < $minTeach) {
$minTeach = $count;
}
}
return $minTeach;
}
// Test cases
$n = 2;
$languages = [[1],[2],[1,2]];
$friendships = [[1,2],[1,3],[2,3]];
echo minimumTeachings($n, $languages, $friendships) . "\n"; // Output: 1
$n = 3;
$languages = [[2],[1,3],[1,2],[3]];
$friendships = [[1,4],[1,2],[3,4],[2,3]];
echo minimumTeachings($n, $languages, $friendships) . "\n"; // Output: 2
?> Explanation:
This approach efficiently narrows down the problem to checking each language individually and determining the optimal language to teach to minimize the number of users needing instruction. The complexity is manageable due to the constraints, making it a practical solution. |
Beta Was this translation helpful? Give feedback.
We need to determine the minimum number of users to teach a single language such that every pair of friends can communicate through a common language. The solution involves checking each language as a candidate and calculating how many users need to learn it to satisfy all friendships that currently lack a common language.
Approach
knows
) where each entryknows[i][j]
indicates whether useri
knows languagej
.