1595. Minimum Cost to Connect Two Groups of Points #443
-
Topics: You are given two groups of points where the first group has The Return the minimum cost it takes to connect the two groups. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can leverage dynamic programming with bitmasking. The idea is to minimize the cost by considering each point in the first group and trying to connect it to all points in the second group. Dynamic Programming (DP) Approach with BitmaskingSteps:
Let's implement this solution in PHP: 1595. Minimum Cost to Connect Two Groups of Points <?php
/**
* @param Integer[][] $cost
* @return Integer
*/
function connectTwoGroups($cost) {
$size1 = count($cost);
$size2 = count($cost[0]);
// Initialize the dp table with a large number (infinity substitute)
$dp = array_fill(0, $size1 + 1, array_fill(0, 1 << $size2, PHP_INT_MAX));
$dp[0][0] = 0;
// Fill the dp table
for ($i = 0; $i < $size1; $i++) {
for ($mask = 0; $mask < (1 << $size2); $mask++) {
for ($j = 0; $j < $size2; $j++) {
$newMask = $mask | (1 << $j);
$dp[$i + 1][$newMask] = min(
$dp[$i + 1][$newMask],
$dp[$i][$mask] + $cost[$i][$j]
);
}
}
}
// Ensure all points in the second group are connected
$finalCost = PHP_INT_MAX;
for ($mask = 0; $mask < (1 << $size2); $mask++) {
$currentCost = $dp[$size1][$mask];
for ($j = 0; $j < $size2; $j++) {
if (!($mask & (1 << $j))) {
$minConnectionCost = PHP_INT_MAX;
for ($i = 0; $i < $size1; $i++) {
$minConnectionCost = min($minConnectionCost, $cost[$i][$j]);
}
$currentCost += $minConnectionCost;
}
}
$finalCost = min($finalCost, $currentCost);
}
return $finalCost;
}
// Example usage:
$cost1 = [[15, 96], [36, 2]];
$cost2 = [[1, 3, 5], [4, 1, 1], [1, 5, 3]];
$cost3 = [[2, 5, 1], [3, 4, 7], [8, 1, 2], [6, 2, 4], [3, 8, 8]];
echo connectTwoGroups($cost1) . "\n"; // Output: 17
echo connectTwoGroups($cost2) . "\n"; // Output: 4
echo connectTwoGroups($cost3) . "\n"; // Output: 10
?> Explanation:
This approach efficiently handles the problem's constraints and ensures the minimum cost for connecting the two groups. |
Beta Was this translation helpful? Give feedback.
We can leverage dynamic programming with bitmasking. The idea is to minimize the cost by considering each point in the first group and trying to connect it to all points in the second group.
Dynamic Programming (DP) Approach with Bitmasking
Steps:
State Representation:
dp[i][mask]
where:i
is the index in the first group (ranging from0
tosize1-1
).mask
is a bitmask representing which points in the second group have been connected.State Transition:
B…