[LeetCode] Minimum Cost to Connect Two Groups of Points

1595. Minimum Cost to Connect Two Groups of Points

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.

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
class Solution {
int dp[13][1<<13];
int dfs(vector<vector<int>>& A, vector<int>& mi, int i, int mask) {
if(i == A.size()) {
int res = 0, n = mi.size();
for(int i = 0; i < n; i++) {
if(mask & (1<<i)) continue;
res += mi[i];
}
return res;
}
if(dp[i][mask] != -1) return dp[i][mask];
int& res = dp[i][mask] = INT_MAX, n = mi.size();

vector<int>& a = A[i];

for(int j = 0; j < n; j++) {
res = min(res, a[j] + dfs(A, mi, i + 1, mask | (1<<j)));
}

return res;
}
public:
int connectTwoGroups(vector<vector<int>>& cost) {
memset(dp, -1, sizeof dp);
int n = cost.size(), m = cost[0].size();
vector<int> mi(m, INT_MAX);
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++)
mi[j] = min(mi[j], cost[i][j]);
}

return dfs(cost, mi, 0, 0);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/01/PS/LeetCode/minimum-cost-to-connect-two-groups-of-points/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.