You are given two groups of points where the first group has size1 points, the second group has size2 points, and size1 >= size2.
The cost of the connection between any two points are given in an size1 x size2 matrix where cost[i][j] is the cost of connecting point i of the first group and point j of the second group. The groups are connected if each point in both groups is connected to one or more points in the opposite group. In other words, each point in the first group must be connected to at least one point in the second group, and each point in the second group must be connected to at least one point in the first group.
Return the minimum cost it takes to connect the two groups.
Input: cost =[[1,3,5],[4,1,1],[1,5,3]]Output: 4Explanation: The optimal way of connecting the groups is:1--A
2--B
2--C
3--A
This results in a total cost of 4.Note that there are multiple points connected to point 2in the first group and point A in the second group. This does not matter as there is no limit to the number of points that can be connected. We only care about the minimum total cost.
We need to connect every point in both groups, minimizing the cost. Since the number of points is small, we can use DP with bitmasking to represent which points in the second group are already connected. For each point in the first group, we try all possible connections to the second group and update the DP state.
classSolution {
funconnectTwoGroups(cost: List<List<Int>>): Int {
val n = cost.size
val m = cost[0].size
val dp = Array(n+1) { IntArray(1 shl m) { Int.MAX_VALUE/2 } }
dp[0][0] = 0for (i in0 until n) {
for (mask in0 until (1 shl m)) {
for (j in0 until m) {
val nmask = mask or (1 shl j)
dp[i+1][nmask] = minOf(dp[i+1][nmask], dp[i][mask] + cost[i][j])
}
}
}
var ans = Int.MAX_VALUE/2for (mask in0 until (1 shl m)) {
if (mask.countOneBits() == m) {
ans = minOf(ans, dp[n][mask])
}
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
defconnectTwoGroups(cost: list[list[int]]) -> int:
n, m = len(cost), len(cost[0])
dp = [[float('inf')] * (1<<m) for _ in range(n+1)]
dp[0][0] =0for i in range(n):
for mask in range(1<<m):
for j in range(m):
nmask = mask | (1<<j)
dp[i+1][nmask] = min(dp[i+1][nmask], dp[i][mask] + cost[i][j])
ans = float('inf')
for mask in range(1<<m):
if bin(mask).count('1') == m:
ans = min(ans, dp[n][mask])
return ans
impl Solution {
pubfnconnect_two_groups(cost: Vec<Vec<i32>>) -> i32 {
let n = cost.len();
let m = cost[0].len();
letmut dp =vec![vec![i32::MAX/2; 1<<m]; n+1];
dp[0][0] =0;
for i in0..n {
for mask in0..(1<<m) {
for j in0..m {
let nmask = mask | (1<<j);
dp[i+1][nmask] = dp[i+1][nmask].min(dp[i][mask] + cost[i][j]);
}
}
}
letmut ans =i32::MAX/2;
for mask in0..(1<<m) {
if mask.count_ones() == m asu32 {
ans = ans.min(dp[n][mask]);
}
}
ans
}
}